cpu_usage.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. cpuSystemUsage := (cpuTimesAfter[0].System - cpuTimesBefore[0].System) / (float64(1000*threadNum) / 1000)
  21. now := time.Now()
  22. u := cpuUsage{
  23. Time: now,
  24. Usage: cpuUserUsage,
  25. }
  26. CpuUserBuffer = append(CpuUserBuffer, u)
  27. s := cpuUsage{
  28. Time: now,
  29. Usage: cpuUserUsage + cpuSystemUsage,
  30. }
  31. CpuTotalBuffer = append(CpuTotalBuffer, s)
  32. if len(CpuUserBuffer) > 200 {
  33. CpuUserBuffer = CpuUserBuffer[1:]
  34. }
  35. if len(CpuTotalBuffer) > 200 {
  36. CpuTotalBuffer = CpuTotalBuffer[1:]
  37. }
  38. // time.Sleep(1 * time.Second)
  39. }
  40. }