feat: 添加 GPU 名称获取功能

This commit is contained in:
Akizon77
2025-05-26 19:12:02 +08:00
parent 6257278426
commit 21b1b17e84
4 changed files with 100 additions and 1 deletions

View File

@@ -0,0 +1,32 @@
//go:build linux
// +build linux
package monitoring
import (
"os/exec"
"strings"
)
func GpuName() string {
accept := []string{"vga", "nvidia", "amd", "radeon", "render"}
out, err := exec.Command("lspci").Output()
if err == nil {
lines := strings.Split(string(out), "\n")
for _, line := range lines {
for _, a := range accept {
if strings.Contains(strings.ToLower(line), a) {
parts := strings.SplitN(line, ":", 4)
if len(parts) >= 4 {
return strings.TrimSpace(parts[3])
} else if len(parts) == 3 {
return strings.TrimSpace(parts[2])
} else if len(parts) == 2 {
return strings.TrimSpace(parts[1])
}
}
}
}
}
return "None"
}

View File

@@ -0,0 +1,13 @@
package monitoring
import (
"testing"
)
func TestGpuName(t *testing.T) {
name := GpuName()
if name == "" || name == "Unknown" {
t.Errorf("Expected GPU name, got empty or 'Unknown'")
}
t.Logf("GPU name: %s", name)
}

View File

@@ -0,0 +1,54 @@
//go:build windows
// +build windows
package monitoring
import (
"strings"
"golang.org/x/sys/windows/registry"
)
func GpuName() string {
displayPath := `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
k, err := registry.OpenKey(registry.LOCAL_MACHINE, displayPath, registry.READ)
if err != nil {
return "Unknown"
}
defer k.Close()
subKeys, err := k.ReadSubKeyNames(-1)
if err != nil {
return "Unknown"
}
gpuName := ""
for _, subKey := range subKeys {
if !strings.HasPrefix(subKey, "0") {
continue
}
fullPath := displayPath + "\\" + subKey
sk, err := registry.OpenKey(registry.LOCAL_MACHINE, fullPath, registry.READ)
if err != nil {
continue
}
defer sk.Close()
deviceDesc, _, err := sk.GetStringValue("DriverDesc")
if err != nil || deviceDesc == "" {
continue
}
deviceDesc = strings.TrimSpace(deviceDesc)
// 只接受支持 OpenGL 的 GPU
openGLVersion, _, err := sk.GetIntegerValue("OpenGLVersion")
if err != nil || openGLVersion == 0 {
continue
}
gpuName += deviceDesc + ", "
}
if gpuName != "" {
return strings.TrimSuffix(gpuName, ", ")
}
return "None"
}