最近踩坑比较多,很大原因就是日志记录不是很完整,因此,最近一直在学习日志的内容。其中有一点就是显卡的信息内容,虽然不是很重要的信息,但是也是有必要的。
常见的查看显卡方式有:
- 任务管理器
- nvidia-smi命令
- nvitop命令
但是以上方式都只能查看,并不能调取其中的显卡信息,因此,在做日志记录的时候并不是十分方便。在查阅过其他大神的方式后,发现 pynvml 库可以满足要求。
pip安装的命令为:
pip install nvidia-ml-py
使用方式
import pynvml
pynvml.nvmlInit()
# 这里的1是GPU id
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
print(meminfo.total /1024/1024 ) #第一块显卡总的显存大小
print(meminfo.used /1024/1024) #这里是字节bytes,所以要想得到以兆M为单位就需要除以1024**2
print(meminfo.free /1024/1024) #第一块显卡剩余显存大小
在终端中输入 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 : b'NVIDIA GeForce RTX 2070'
nvmlShutdown()
对于使用 logger 记录的小伙伴,可以直接将以下代码添加到 logger中,其中 nvmlInit()/nvmlShutdown()
是必须的,否则无法使用。此外 socket.gethostname()
可以获取主机名称,便于更好的记录日志。
logger.info(f">>> Host name \t: {socket.gethostname()}")
nvmlInit()
logger.info(f"Driver Version : {nvmlSystemGetDriverVersion()}") # 显卡驱动版本
deviceCount = nvmlDeviceGetCount() # 几块显卡
for i in range(deviceCount):
handle = nvmlDeviceGetHandleByIndex(i)
logger.info(f"Device {i, ' : ', nvmlDeviceGetName(handle)}")
nvmlShutdown()