Skip to content

Commit 7e1b45d

Browse files
committed
Add warmup counter to EWMA rate
1 parent ef3ece3 commit 7e1b45d

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

pkg/util/math/rate.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ import (
1212
"go.uber.org/atomic"
1313
)
1414

15+
const (
16+
warmupSamples uint8 = 10
17+
)
18+
1519
// EwmaRate tracks an exponentially weighted moving average of a per-second rate.
1620
type EwmaRate struct {
1721
newEvents atomic.Int64
@@ -22,6 +26,7 @@ type EwmaRate struct {
2226
mutex sync.RWMutex
2327
lastRate float64
2428
init bool
29+
count uint8
2530
}
2631

2732
func NewEWMARate(alpha float64, interval time.Duration) *EwmaRate {
@@ -35,6 +40,12 @@ func NewEWMARate(alpha float64, interval time.Duration) *EwmaRate {
3540
func (r *EwmaRate) Rate() float64 {
3641
r.mutex.RLock()
3742
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+
3849
return r.lastRate
3950
}
4051

@@ -46,6 +57,10 @@ func (r *EwmaRate) Tick() {
4657
r.mutex.Lock()
4758
defer r.mutex.Unlock()
4859

60+
if r.count < warmupSamples {
61+
r.count++
62+
}
63+
4964
if r.init {
5065
r.lastRate += r.alpha * (instantRate - r.lastRate)
5166
} else {

pkg/util/math/rate_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,17 @@ func TestRate(t *testing.T) {
1717
events int
1818
want float64
1919
}{
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+
2031
{60, 1},
2132
{30, 0.9},
2233
{0, 0.72},

0 commit comments

Comments
 (0)