天天看點

【Python管理GPU】pynvml工具的安裝與使用

可以利用python工具pynvml來實作顯示卡資訊的讀取與管理

Nvidia的顯示卡提供了NVML(英偉達顯示卡管理庫)以及建構在其上的nvidia-smi(顯示卡系統管理界面),可以友善的查詢顯示卡的資訊和工作狀況。在python中同樣可以利用pynvml庫來實作顯示卡資訊的擷取。

1.安裝

可以使用

pip

友善的安裝:

pip install nvidia-ml-py

#也可以根據python版本制定2/3
#python2
pip install nvidia-ml-py2

#python3
pip install nvidia-ml-py3

#或者使用源碼安裝
#下載下傳連結:http://pypi.python.org/pypi/nvidia-ml-py/
sudo python setup.py install


#e.g
~$ pip install nvidia-ml-py3
>>>
Collecting nvidia-ml-py3
>>>  Downloading 
>>> https://files.pythonhosted.org/packages/6d/64/cce82bddb80c0b0f5c703bbdafa94bfb69a1c5ad7a79cff00b482468f0d3/nvidia-ml-py3-7.352.0.tar.gz
>>>  Building wheels for collected packages: nvidia-ml-py3
>>>  Running setup.py bdist_wheel for nvidia-ml-py3 ... done
>>>  Stored in directory: xxxxxxx/xxxxxx/xxxxx
Successfully built nvidia-ml-py3
Installing collected packages: nvidia-ml-py3
Successfully installed nvidia-ml-py3-7.352.0
           

2.使用

#簡單使用
from pynvml import *
nvmlInit()     #初始化
print("Driver: "nvmlSystemGetDriverVersion())  #顯示驅動資訊
#>>> Driver: 384.xxx

#檢視裝置
deviceCount = nvmlDeviceGetCount()
for i in range(deviceCount):
    handle = nvmlDeviceGetHandleByIndex(i)
    print("GPU", i, ":", nvmlDeviceGetName(handle))
#>>>
#GPU 0 : b'GeForce GTX 1080 Ti'
#GPU 1 : b'GeForce GTX 1080 Ti'

#檢視顯存、溫度、風扇、電源
handle = nvmlDeviceGetHandleByIndex(0)
info = nvmlDeviceGetMemoryInfo(handle)
print("Memory Total: ",info.total)
print("Memory Free: ",info.free)
print("Memory Used: ",info.used)

print("Temperature is %d C"%nvmlDeviceGetTemperature(handle,0))
print("Fan speed is "nvmlDeviceGetFanSpeed(handle))
print("Power ststus",nvmlDeviceGetPowerState(handle))


#最後要關閉管理工具
nvmlShutdown()


#nvmlDeviceXXX有一系列函數可以調用,包括了NVML的大多數函數。
#具體可以參考:https://docs.nvidia.com/deploy/nvml-api/group__nvmlDeviceQueries.html#group__nvmlDeviceQueries
           
【Python管理GPU】pynvml工具的安裝與使用

nvml:https://docs.nvidia.com/deploy/nvml-api/group__nvmlDeviceQueries.html#group__nvmlDeviceQueries

pypi:https://pypi.org/project/nvidia-ml-py/

usage:https://pythonhosted.org/nvidia-ml-py/

nvidia_smi:https://github.com/ultrabug/py3status/blob/master/py3status/modules/nvidia_smi.py

py3status:https://py3status.readthedocs.io/en/latest/modules.html

unsplash:https://unsplash.com/

pexels:https://www.pexels.com/