File tree Expand file tree Collapse file tree 2 files changed +26
-0
lines changed Expand file tree Collapse file tree 2 files changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -12,6 +12,10 @@ import (
12
12
"go.uber.org/atomic"
13
13
)
14
14
15
+ const (
16
+ warmupSamples uint8 = 10
17
+ )
18
+
15
19
// EwmaRate tracks an exponentially weighted moving average of a per-second rate.
16
20
type EwmaRate struct {
17
21
newEvents atomic.Int64
@@ -22,6 +26,7 @@ type EwmaRate struct {
22
26
mutex sync.RWMutex
23
27
lastRate float64
24
28
init bool
29
+ count uint8
25
30
}
26
31
27
32
func NewEWMARate (alpha float64 , interval time.Duration ) * EwmaRate {
@@ -35,6 +40,12 @@ func NewEWMARate(alpha float64, interval time.Duration) *EwmaRate {
35
40
func (r * EwmaRate ) Rate () float64 {
36
41
r .mutex .RLock ()
37
42
defer r .mutex .RUnlock ()
43
+
44
+ // until the first `warmupSamples` have been seen, the moving average is "not ready" to be queried
45
+ if r .count < warmupSamples {
46
+ return 0.0
47
+ }
48
+
38
49
return r .lastRate
39
50
}
40
51
@@ -46,6 +57,10 @@ func (r *EwmaRate) Tick() {
46
57
r .mutex .Lock ()
47
58
defer r .mutex .Unlock ()
48
59
60
+ if r .count < warmupSamples {
61
+ r .count ++
62
+ }
63
+
49
64
if r .init {
50
65
r .lastRate += r .alpha * (instantRate - r .lastRate )
51
66
} else {
Original file line number Diff line number Diff line change @@ -17,6 +17,17 @@ func TestRate(t *testing.T) {
17
17
events int
18
18
want float64
19
19
}{
20
+ // warm-up samples
21
+ {60 , 0 },
22
+ {60 , 0 },
23
+ {60 , 0 },
24
+ {60 , 0 },
25
+ {60 , 0 },
26
+ {60 , 0 },
27
+ {60 , 0 },
28
+ {60 , 0 },
29
+ {60 , 0 },
30
+
20
31
{60 , 1 },
21
32
{30 , 0.9 },
22
33
{0 , 0.72 },
You can’t perform that action at this time.
0 commit comments