-
Notifications
You must be signed in to change notification settings - Fork 29
/
manager.go
47 lines (40 loc) · 931 Bytes
/
manager.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
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package trackers
import (
"sync"
)
var SharedManager = NewManager()
type Manager struct {
m map[string][]float64 // label => time costs ms
locker sync.Mutex
}
func NewManager() *Manager {
return &Manager{m: map[string][]float64{}}
}
func (this *Manager) Add(label string, costMs float64) {
this.locker.Lock()
costs, ok := this.m[label]
if ok {
costs = append(costs, costMs)
if len(costs) > 5 { // 只取最近的N条
costs = costs[1:]
}
this.m[label] = costs
} else {
this.m[label] = []float64{costMs}
}
this.locker.Unlock()
}
func (this *Manager) Labels() map[string]float64 {
var result = map[string]float64{}
this.locker.Lock()
for label, costs := range this.m {
var sum float64
for _, cost := range costs {
sum += cost
}
result[label] = sum / float64(len(costs))
}
this.locker.Unlock()
return result
}