【Python管理GPU】pynvml工具的安装与使用

可以利用python可以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

在这里插入图片描述


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/

原文地址:https://www.cnblogs.com/Tom-Ren/p/10024298.html