-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnvml_collector.go
60 lines (47 loc) · 1022 Bytes
/
nvml_collector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"errors"
"github.com/NVIDIA/go-nvml/pkg/nvml"
)
type NVMLCollector struct {
device nvml.Device
}
type MemoryInfo struct {
UsedMB int
TotalMB int
FreeMB int
}
func NewNVMLCollector() (*NVMLCollector, error) {
if err := nvml.Init(); err != nvml.SUCCESS {
return nil, err
}
count, err := nvml.DeviceGetCount()
if err != nvml.SUCCESS {
return nil, err
}
if count == 0 {
return nil, errors.New("no NVIDIA GPU found")
}
device, err := nvml.DeviceGetHandleByIndex(0)
if err != nvml.SUCCESS {
return nil, err
}
return &NVMLCollector{device: device}, nil
}
func (nc *NVMLCollector) GetVRAMUsage() (MemoryInfo, error) {
memory, err := nc.device.GetMemoryInfo()
if err != nvml.SUCCESS {
return MemoryInfo{}, err
}
byteToMB := func(n uint64) int {
return int(n / (1 << 20))
}
return MemoryInfo{
UsedMB: byteToMB(memory.Used),
TotalMB: byteToMB(memory.Total),
FreeMB: byteToMB(memory.Free),
}, nil
}
func (nc *NVMLCollector) Close() {
nvml.Shutdown()
}