cpu_usage.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package tool
  2. import (
  3. "github.com/shirou/gopsutil/v3/cpu"
  4. "runtime"
  5. "time"
  6. )
  7. type cpuUsage struct {
  8. Time time.Time `json:"x"`
  9. Usage float64 `json:"y"`
  10. }
  11. var CpuUserBuffer []cpuUsage
  12. var CpuTotalBuffer []cpuUsage
  13. func RecordCpuUsage() {
  14. for {
  15. cpuTimesBefore, _ := cpu.Times(false)
  16. time.Sleep(1000 * time.Millisecond)
  17. cpuTimesAfter, _ := cpu.Times(false)
  18. threadNum := runtime.GOMAXPROCS(0)
  19. cpuUserUsage := (cpuTimesAfter[0].User - cpuTimesBefore[0].User) / (float64(1000*threadNum) / 1000)
  20. cpuUserUsage *= 100
  21. cpuSystemUsage := (cpuTimesAfter[0].System - cpuTimesBefore[0].System) / (float64(1000*threadNum) / 1000)
  22. cpuSystemUsage *= 100
  23. now := time.Now()
  24. u := cpuUsage{
  25. Time: now,
  26. Usage: cpuUserUsage,
  27. }
  28. CpuUserBuffer = append(CpuUserBuffer, u)
  29. s := cpuUsage{
  30. Time: now,
  31. Usage: cpuUserUsage + cpuSystemUsage,
  32. }
  33. CpuTotalBuffer = append(CpuTotalBuffer, s)
  34. if len(CpuUserBuffer) > 200 {
  35. CpuUserBuffer = CpuUserBuffer[1:]
  36. }
  37. if len(CpuTotalBuffer) > 200 {
  38. CpuTotalBuffer = CpuTotalBuffer[1:]
  39. }
  40. }
  41. }