diff --git a/Software/Development/Language/Go/Package/Gopsutil/Golang_获取硬件参数及_CPU_内存_硬盘的使用率.md b/Software/Development/Language/Go/Package/Gopsutil/Golang_获取硬件参数及_CPU_内存_硬盘的使用率.md new file mode 100644 index 0000000..98c65bf --- /dev/null +++ b/Software/Development/Language/Go/Package/Gopsutil/Golang_获取硬件参数及_CPU_内存_硬盘的使用率.md @@ -0,0 +1,60 @@ +# Golang 获取硬件参数及 CPU/内存/硬盘 的使用率 + +## 1. 安装软件包 + +```bash +go get github.com/tklauser/go-sysconf +go get golang.org/x/sys/unix +go get github.com/shirou/gopsutil +``` + +## 2. 示例代码 + +```go +package main + +import ( + "fmt" + "time" + + "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/mem" +) + +func GetCoreCount() int { + cpuInfo, _ := cpu.Info() + return len(cpuInfo) +} + +func GetModelName(idx int) string { + cpuInfo, _ := cpu.Info() + return cpuInfo[idx].ModelName +} + +func GetCpuPercent() float64 { + percent, _ := cpu.Percent(time.Second, false) + return percent[0] +} + +func GetMemPercent() float64 { + memInfo, _ := mem.VirtualMemory() + return 100.0 * float64(memInfo.Total-memInfo.Available) / float64(memInfo.Total) +} + +func GetDiskPercent() float64 { + diskInfo, _ := disk.Usage("/") + return diskInfo.UsedPercent +} + +func main() { + fmt.Println("Model Name: ", GetModelName(0)) + fmt.Println("Core count: ", GetCoreCount()) + for { + fmt.Println("CPU: ", GetCpuPercent()) + fmt.Println("Mem: ", GetMemPercent()) + fmt.Println("Dsk: ", GetDiskPercent()) + time.Sleep(1 * time.Second) + } +} +``` \ No newline at end of file