Skip to content

Commit

Permalink
GetInstantaneous returns the rate
Browse files Browse the repository at this point in the history
Signed-off-by: bufferflies <1045931706@qq.com>
  • Loading branch information
bufferflies committed Apr 12, 2023
1 parent fb22d1e commit ccb9fbf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
13 changes: 11 additions & 2 deletions pkg/movingaverage/avg_over_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type deltaWithInterval struct {
// then calculates the change rate by (sum of changes) / (sum of intervals).
type AvgOverTime struct {
que *queue.Queue // The element is `deltaWithInterval`, sum of all elements' interval is less than `avgInterval`
margin deltaWithInterval // The last element from `PopFront` in `que`
margin deltaWithInterval // The last element from `PopFront` in `que`, it will be changed if the sum exclude it is greater than `avgInterval`
deltaSum float64 // Including `margin` and all elements in `que`
intervalSum time.Duration // Including `margin` and all elements in `que`
avgInterval time.Duration
Expand Down Expand Up @@ -76,6 +76,11 @@ func (aot *AvgOverTime) Clear() {
}

// Add adds recent change to AvgOverTime.
// It will pop item until the retain item's sum is greater than avgInterval.
// such as:
// que [1,1,1,6], avgInterval is 5.
// It will pop 6 if adding 2, the retaining item's sum is 5(2,1,1,1) >= avgInterval.
// It can't pop 6 if adding 1, the retaining item's sum is 4(1,1,1,1) < avgInterval.
func (aot *AvgOverTime) Add(delta float64, interval time.Duration) {
if interval == 0 {
return
Expand Down Expand Up @@ -136,7 +141,11 @@ func (aot *AvgOverTime) GetIntervalSum() time.Duration {
// GetInstantaneous returns the value just added.
func (aot *AvgOverTime) GetInstantaneous() float64 {
if aot.que.Len() == 0 || aot.que.Back() == nil {
if aot.margin.interval != 0 {
return aot.margin.delta / aot.margin.interval.Seconds()
}
return aot.margin.delta
}
return aot.que.Back().(deltaWithInterval).delta
data := aot.que.Back().(deltaWithInterval)
return data.delta / data.interval.Seconds()
}
5 changes: 3 additions & 2 deletions pkg/movingaverage/avg_over_time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,13 @@ func TestPulse2(t *testing.T) {
re := require.New(t)
dur := 5 * time.Second
aot := NewAvgOverTime(dur)
re.Equal(float64(0), aot.GetInstantaneous())
aot.Add(1000, dur)
re.Equal(float64(1000), aot.GetInstantaneous())
re.Equal(float64(1000)/dur.Seconds(), aot.GetInstantaneous())
re.True(aot.IsFull())
aot.Clear()
aot.Add(1000, dur)
re.Equal(float64(1000), aot.GetInstantaneous())
re.Equal(float64(1000)/dur.Seconds(), aot.GetInstantaneous())
}

func TestChange(t *testing.T) {
Expand Down

0 comments on commit ccb9fbf

Please sign in to comment.