-
Notifications
You must be signed in to change notification settings - Fork 1
/
rolling_window.go
63 lines (53 loc) · 910 Bytes
/
rolling_window.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
61
62
63
package main
import (
"time"
)
const (
windowSize = 10
)
type RollingWindow struct {
slots []int
count int
tail int
last time.Time
d time.Duration
}
func NewRollingWindow(d time.Duration) *RollingWindow {
return &RollingWindow{
slots: make([]int, windowSize),
last: time.Now(),
d: d / windowSize,
}
}
func (r *RollingWindow) clear() {
r.last = time.Now()
for i := 0; i < windowSize; i++ {
r.slots[i] = 0
}
r.tail = 0
r.count = 0
}
func (r *RollingWindow) roll() {
d := time.Since(r.last)
n := int(d / r.d)
// Completely wipe out.
if n >= windowSize {
r.clear()
return
}
for i := 0; i < n; i++ {
r.tail = (r.tail + 1) % len(r.slots)
r.count -= r.slots[r.tail]
r.slots[r.tail] = 0
r.last = r.last.Add(r.d)
}
}
func (r *RollingWindow) Inc() {
r.roll()
r.slots[r.tail]++
r.count++
}
func (r *RollingWindow) Count() int {
r.roll()
return r.count
}