main.go 786 B

12345678910111213141516171819202122232425262728293031323334
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/shirou/gopsutil/cpu"
  5. "github.com/shirou/gopsutil/disk"
  6. "github.com/shirou/gopsutil/mem"
  7. "time"
  8. )
  9. // GetCpuPercent cpu总占用率
  10. func GetCpuPercent() float64 {
  11. percent, _ := cpu.Percent(time.Second, false)
  12. return percent[0]
  13. }
  14. // GetMemoryPercent 内存总占用率
  15. func GetMemoryPercent() float64 {
  16. memory, _ := mem.SwapMemory()
  17. return memory.UsedPercent
  18. }
  19. // GetDiskPercent 磁盘总占用率
  20. func GetDiskPercent() float64 {
  21. parts, _ := disk.Partitions(true)
  22. diskInfo, _ := disk.Usage(parts[0].Mountpoint)
  23. return diskInfo.UsedPercent
  24. }
  25. func main() {
  26. fmt.Println("cpu总占用率为:", GetCpuPercent())
  27. fmt.Println("内存总占用率为:", GetMemoryPercent())
  28. fmt.Println("磁盘总占用率为:", GetDiskPercent())
  29. }