usage.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package stat
  2. import (
  3. "runtime"
  4. "sync/atomic"
  5. "time"
  6. "github.com/tal-tech/go-zero/core/logx"
  7. "github.com/tal-tech/go-zero/core/stat/internal"
  8. "github.com/tal-tech/go-zero/core/threading"
  9. )
  10. const (
  11. // 250ms and 0.95 as beta will count the average cpu load for past 5 seconds
  12. cpuRefreshInterval = time.Millisecond * 250
  13. allRefreshInterval = time.Minute
  14. // moving average beta hyperparameter
  15. beta = 0.95
  16. )
  17. var cpuUsage int64
  18. func init() {
  19. go func() {
  20. cpuTicker := time.NewTicker(cpuRefreshInterval)
  21. defer cpuTicker.Stop()
  22. allTicker := time.NewTicker(allRefreshInterval)
  23. defer allTicker.Stop()
  24. for {
  25. select {
  26. case <-cpuTicker.C:
  27. threading.RunSafe(func() {
  28. curUsage := internal.RefreshCpu()
  29. prevUsage := atomic.LoadInt64(&cpuUsage)
  30. // cpu = cpuᵗ⁻¹ * beta + cpuᵗ * (1 - beta)
  31. usage := int64(float64(prevUsage)*beta + float64(curUsage)*(1-beta))
  32. atomic.StoreInt64(&cpuUsage, usage)
  33. })
  34. case <-allTicker.C:
  35. printUsage()
  36. }
  37. }
  38. }()
  39. }
  40. // CpuUsage returns current cpu usage.
  41. func CpuUsage() int64 {
  42. return atomic.LoadInt64(&cpuUsage)
  43. }
  44. func bToMb(b uint64) float32 {
  45. return float32(b) / 1024 / 1024
  46. }
  47. func printUsage() {
  48. var m runtime.MemStats
  49. runtime.ReadMemStats(&m)
  50. logx.Statf("CPU: %dm, MEMORY: Alloc=%.1fMi, TotalAlloc=%.1fMi, Sys=%.1fMi, NumGC=%d",
  51. CpuUsage(), bToMb(m.Alloc), bToMb(m.TotalAlloc), bToMb(m.Sys), m.NumGC)
  52. }