cpu.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package gupta
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. // collect all CPU stat from /proc/cpustat
  8. type CPUStat struct {
  9. totalTime float64
  10. idleTime float64
  11. totalTimeNew float64
  12. idleTimeNew float64
  13. }
  14. func (c *CPUStat) ReadInfoNew(statline string) {
  15. rawInfo := strings.Fields(statline)
  16. idleNew, _ := strconv.ParseFloat(rawInfo[4], 10)
  17. iowaitNew, _ := strconv.ParseFloat(rawInfo[5], 10)
  18. c.idleTimeNew = idleNew + iowaitNew
  19. for _, s := range rawInfo {
  20. u, _ := strconv.ParseFloat(s, 10)
  21. c.totalTimeNew += u
  22. }
  23. }
  24. func (c *CPUStat) ReadInfo(statline string) {
  25. rawInfo := strings.Fields(statline)
  26. for _, s := range rawInfo[1:] {
  27. u, _ := strconv.ParseFloat(s, 10)
  28. c.totalTime += u
  29. }
  30. idle, _ := strconv.ParseFloat(rawInfo[4], 10)
  31. iowait, _ := strconv.ParseFloat(rawInfo[5], 10)
  32. c.idleTime = idle + iowait
  33. }
  34. func (c *CPUStat) CPUUsage() float64 {
  35. deltaIdleTime := c.idleTimeNew - c.idleTime
  36. deltaTotalTime := c.totalTimeNew - c.totalTime
  37. cpuUsage := (1.0 - float64(deltaIdleTime)/float64(deltaTotalTime)) * 100
  38. return cpuUsage
  39. }
  40. func NewCPUStat(procstatline, procstatlineNew string) CPUStat {
  41. cpustat := CPUStat{}
  42. cpustat.ReadInfo(procstatline)
  43. cpustat.ReadInfoNew(procstatlineNew)
  44. return cpustat
  45. }
  46. func (c CPUStat) MarshalJSON() ([]byte, error) {
  47. jsonData := []byte(
  48. fmt.Sprintf("{\"cpu usage\": \"%.2f%%\"}", c.CPUUsage()))
  49. return jsonData, nil
  50. }