windows 下 go 通过 nvml 获取显卡的温度
通过go的syscall 来调用 nvml.dll(这个文件一般在system32下可以直接访问,或者在 “C:\Program Files\NVIDIA Corporation\NVSMI”这个目录下)
import (
"C"
"fmt"
"syscall"
"unsafe"
"winbase_exporter/nvml"
)
type Device uintptr
const TemperatureGPU = nvml.TemperatureSensor(0)
func main() {
//加载NVML动态库并初始化
nvml := syscall.NewLazyDLL("nvml.dll")
initProc := nvml.NewProc("nvmlInit")
_, _, _ = initProc.Call()
//通过下标索引来获取显卡设备的句柄
var device uintptr
deviceProc := nvml.NewProc("nvmlDeviceGetHandleByIndex")
_, _, _ = deviceProc.Call(0, uintptr(unsafe.Pointer(&device)))
//获取下标0的的显卡温度
var temp uint
tempProc := nvml.NewProc("nvmlDeviceGetTemperature")
_, _, _ = tempProc.Call(uintptr(device), uintptr(TemperatureGPU), uintptr(unsafe.Pointer(&temp)))
fmt.Println(temp)
通过wmi获取主机下的所有显卡信息
type GpuInfo struct {
Name string
DeviceID string
AdapterRAM int
AdapterDACType string
Monochrome bool
InstalledDisplayDrivers string
DriverVersion string
VideoProcessor string
VideoArchitecture int
VideoMemoryType int
}
func getGpuInfo() (gpuinfo []GpuInfo) {
err := wmi.Query("select * from Win32_VideoController", &gpuinfo)
if err != nil {
panic(err)
}
return
}
github.com/mxpv/nvml-go 是一个用syscall调用nvml.dll封装比较好的库,推荐使用这个库在做windows获取显卡信息。
import nvml "github.com/mxpv/nvml-go"
n, err := nvml.New("nvml.dll")
if err != nil {
panic(err)
}
defer n.Shutdown()
err = n.Init()
if err != nil {
panic(err)
}
device, err := n.DeviceGetHandleByIndex(0)
temp, err := n.DeviceGetTemperature(device, TemperatureGPU)
fmt.Println(temp)
github.com/mindprince/gonvml 这个是go在lnuix平台下,调用nvml.h来管理显卡的库。
python获取显卡温度的方法,pynvml同样是使用了nvml
import pynvml
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
gpuTemperature = pynvml.nvmlDeviceGetTemperature(handle, 0)
print(gpuTemperature)
nvidia-smi 是官方工具可以直接查看显卡信息
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: