-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrate_monitor.go
51 lines (40 loc) · 1020 Bytes
/
rate_monitor.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
package logtop
import (
"time"
)
type RateMonitor struct {
lastSnapshotExists bool
lastSnapshotAt time.Time
counts map[string]uint64
}
func (mon *RateMonitor) Record(val string) {
if current, ok := mon.counts[val]; ok {
mon.counts[val] = current + 1
} else {
mon.counts[val] = 1
}
}
// returns a set of rates since the last snapshot
func (mon *RateMonitor) Snapshot() map[string]float64 {
currentTime := time.Now()
// first time around, no rates to return
if !mon.lastSnapshotExists {
mon.lastSnapshotExists = true
mon.lastSnapshotAt = currentTime
mon.counts = make(map[string]uint64)
return make(map[string]float64)
}
interval := currentTime.Sub(mon.lastSnapshotAt)
rates := make(map[string]float64)
for key, count := range mon.counts {
rates[key] = float64(count) / interval.Seconds()
}
mon.lastSnapshotAt = currentTime
mon.counts = make(map[string]uint64)
return rates
}
func NewRateMonitor() *RateMonitor {
return &RateMonitor{
counts: make(map[string]uint64),
}
}