Skip to content

Commit ac939d1

Browse files
authored
fix TimedSlidingWindowI64 bug of start index incorrectly wraped around (#24)
1 parent c3d609e commit ac939d1

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

times/timedSlidingWindow.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ package times
22

33
import (
44
"time"
5-
6-
"github.com/jf-tech/go-corelib/maths"
75
)
86

97
/*
@@ -108,9 +106,10 @@ func (t *TimedSlidingWindowI64) Add(amount int64) {
108106
t.buckets[i%t.n] = 0
109107
}
110108
t.end = (t.start + idx) % t.n
111-
newStart := maths.MaxInt(t.start+idx-t.n+1, t.start)
112-
t.startTime = t.startTime.Add(time.Duration(newStart-t.start) * t.bucket)
113-
t.start = newStart
109+
if idx >= t.n {
110+
t.startTime = t.startTime.Add(time.Duration(idx-t.n+1) * t.bucket)
111+
t.start = (t.start + idx - t.n + 1) % t.n
112+
}
114113
t.buckets[t.end] += amount
115114
t.total += amount
116115
} else {

times/timedSlidingWindow_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,26 @@ func TestTimedSlidingWindowI64(t *testing.T) {
6565
})
6666
}
6767

68+
func TestTimedSlidingWindowI64_ContinousIncr(t *testing.T) {
69+
tc := &testClock{}
70+
sw := NewTimedSlidingWindowI64(5*time.Second, 1*time.Second, tc)
71+
test := func(adv time.Duration, add int64, expected []int64) {
72+
tc.adv(adv)
73+
sw.Add(add)
74+
assert.Equal(t, expected, sw.buckets)
75+
total := int64(0)
76+
for i := 0; i < len(expected); i++ {
77+
total += expected[i]
78+
}
79+
assert.Equal(t, total, sw.Total())
80+
}
81+
expected := []int64{0, 0, 0, 0, 0}
82+
for i := 0; i < 100; i++ {
83+
expected[(i+1)%len(expected)] = int64(i)
84+
test(time.Second, int64(i), expected)
85+
}
86+
}
87+
6888
const (
6989
tswBenchSeed = int64(1234)
7090
tswBenchWindow = time.Minute

0 commit comments

Comments
 (0)