From 127ef4381ebf3e8ea576731f2f9e6f1d19860c4a Mon Sep 17 00:00:00 2001 From: "chen.yang" Date: Thu, 19 Aug 2021 14:28:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20Golang=20=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E7=A1=AC=E4=BB=B6=E5=8F=82=E6=95=B0=E5=8F=8A=20CPU/?= =?UTF-8?q?=E5=86=85=E5=AD=98/=E7=A1=AC=E7=9B=98=20=E7=9A=84=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E7=8E=87.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chen.yang --- ...ng_获取硬件参数及_CPU_内存_硬盘的使用率.md | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Software/Development/Language/Go/Package/Gopsutil/Golang_获取硬件参数及_CPU_内存_硬盘的使用率.md 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