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