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