Skip to content

Commit

Permalink
Add warmup counter to EWMA rate
Browse files Browse the repository at this point in the history
  • Loading branch information
slimjim777 committed Oct 12, 2024
1 parent ef3ece3 commit 7e1b45d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/util/math/rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import (
"go.uber.org/atomic"
)

const (
warmupSamples uint8 = 10
)

// EwmaRate tracks an exponentially weighted moving average of a per-second rate.
type EwmaRate struct {
newEvents atomic.Int64
Expand All @@ -22,6 +26,7 @@ type EwmaRate struct {
mutex sync.RWMutex
lastRate float64
init bool
count uint8
}

func NewEWMARate(alpha float64, interval time.Duration) *EwmaRate {
Expand All @@ -35,6 +40,12 @@ func NewEWMARate(alpha float64, interval time.Duration) *EwmaRate {
func (r *EwmaRate) Rate() float64 {
r.mutex.RLock()
defer r.mutex.RUnlock()

// until the first `warmupSamples` have been seen, the moving average is "not ready" to be queried
if r.count < warmupSamples {
return 0.0
}

return r.lastRate
}

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

if r.count < warmupSamples {
r.count++
}

if r.init {
r.lastRate += r.alpha * (instantRate - r.lastRate)
} else {
Expand Down
11 changes: 11 additions & 0 deletions pkg/util/math/rate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ func TestRate(t *testing.T) {
events int
want float64
}{
// warm-up samples
{60, 0},
{60, 0},
{60, 0},
{60, 0},
{60, 0},
{60, 0},
{60, 0},
{60, 0},
{60, 0},

{60, 1},
{30, 0.9},
{0, 0.72},
Expand Down

0 comments on commit 7e1b45d

Please sign in to comment.