usage.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. func CpuUsage() int64 {
  41. return atomic.LoadInt64(&cpuUsage)
  42. }
  43. func bToMb(b uint64) float32 {
  44. return float32(b) / 1024 / 1024
  45. }
  46. func printUsage() {
  47. var m runtime.MemStats
  48. runtime.ReadMemStats(&m)
  49. logx.Statf("CPU: %dm, MEMORY: Alloc=%.1fMi, TotalAlloc=%.1fMi, Sys=%.1fMi, NumGC=%d",
  50. CpuUsage(), bToMb(m.Alloc), bToMb(m.TotalAlloc), bToMb(m.Sys), m.NumGC)
  51. }