需要使用pynvml库
官网:https://pythonhosted.org/nvidia-ml-py/
下载文件地址:https://pypi.org/project/nvidia-ml-py/#history
现阶段pip安装的命令为:
sudo pip install nvidia-ml-py
具体实例
import pynvml
pynvml.nvmlInit()
# 这里的1是GPU id
handle = pynvml.nvmlDeviceGetHandleByIndex(1)
meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
print(meminfo.total) #第二块显卡总的显存大小
print(meminfo.used)#这里是字节bytes,所以要想得到以兆M为单位就需要除以1024**2
print(meminfo.free) #第二块显卡剩余显存大小
输出是:
11721506816
5333057536
6388449280
经过计算,总的现存大小11721506816 / 1024 /1024 = 11178M, 已使用5333057536 / 1024 /1024 =5086M,然后在ubuntu终端中输入nvidia-smi查看显卡信息:
其他实例
>>> from pynvml import *
>>> nvmlInit()
>>> print "Driver Version:", nvmlSystemGetDriverVersion()#显卡驱动版本
Driver Version: 304.00
>>> deviceCount = nvmlDeviceGetCount()#几块显卡
>>> for i in range(deviceCount):
... handle = nvmlDeviceGetHandleByIndex(i)
... print "Device", i, ":", nvmlDeviceGetName(handle) #具体是什么显卡
...
Device 0 : Tesla C2070
>>> nvmlShutdown()