-
Notifications
You must be signed in to change notification settings - Fork 0
/
nvsmi.py
92 lines (73 loc) · 2.18 KB
/
nvsmi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# NVIDIA SMI utility interface
# Imports
from pynvml.smi import *
# NVIDIA SMI user class
# noinspection PyPep8Naming
class NvidiaSMI:
def __init__(self):
self._impl = _NvidiaSMI.getInstance()
def __del__(self):
self._impl = None
_NvidiaSMI.ungetInstance()
def DeviceQuery(self, *args, **kwargs):
return self._impl.DeviceQuery(*args, **kwargs)
def XmlDeviceQuery(self, *args, **kwargs):
return self._impl.XmlDeviceQuery(*args, **kwargs)
def format(self, *args, **kwargs):
return self._impl.format(*args, **kwargs)
# NVIDIA SMI wrapper metaclass
class _NvidiaSMIMeta(type):
@property
def _nvidia_smi__handles(cls):
# noinspection PyUnresolvedReferences
return cls._NvidiaSMI__handles
# NVIDIA SMI wrapper class
# noinspection PyPep8Naming
class _NvidiaSMI(metaclass=_NvidiaSMIMeta):
__instance = None
__handles = None
__ref_count = 0
@staticmethod
def getInstance():
if _NvidiaSMI.__instance is None:
_NvidiaSMI.__ref_count = 1
_NvidiaSMI()
elif _NvidiaSMI.__ref_count >= 0:
_NvidiaSMI.__ref_count += 1
else:
_NvidiaSMI.__ref_count = 1
return _NvidiaSMI.__instance
@staticmethod
def ungetInstance():
_NvidiaSMI.__ref_count -= 1
if _NvidiaSMI.__ref_count <= 0:
_NvidiaSMI.__deleteInstance()
@staticmethod
def __deleteInstance():
_NvidiaSMI.__instance = None
_NvidiaSMI.__ref_count = 0
_NvidiaSMI.__deinitialise_nvml()
def __init__(self):
if _NvidiaSMI.__instance is None and _NvidiaSMI.__ref_count == 1:
_NvidiaSMI.__instance = self
_NvidiaSMI.__initialise_nvml()
else:
raise Exception("This class should only be instantiated using getInstance()")
def __del__(self):
if _NvidiaSMI.__instance is not None and _NvidiaSMI.__instance is self:
_NvidiaSMI.__deleteInstance()
@staticmethod
def __initialise_nvml():
nvmlInit()
device_count = nvmlDeviceGetCount()
_NvidiaSMI.__handles = {}
for i in range(device_count):
_NvidiaSMI.__handles[i] = nvmlDeviceGetHandleByIndex(i)
@staticmethod
def __deinitialise_nvml():
_NvidiaSMI.__handles = None
nvmlShutdown()
def DeviceQuery(self, *args, **kwargs):
# noinspection PyUnresolvedReferences
return nvidia_smi.DeviceQuery.__func__(self.__class__, *args, **kwargs)
# EOF