增加 Golang 获取硬件参数及 CPU/内存/硬盘 的使用率.
Signed-off-by: chen.yang <chen.yang@yuzhen-iot.com>
This commit is contained in:
parent
35c4af64ed
commit
127ef4381e
|
@ -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)
|
||||
}
|
||||
}
|
||||
```
|
Loading…
Reference in New Issue