diff --git a/memmetrics/counter.go b/memmetrics/counter.go index cab92aa..5a7578a 100644 --- a/memmetrics/counter.go +++ b/memmetrics/counter.go @@ -131,9 +131,9 @@ func (c *RollingCounter) getBucket(t time.Time) int { func (c *RollingCounter) cleanup() { now := clock.Now().UTC() for i := 0; i < len(c.values); i++ { - now = now.Add(time.Duration(-1*i) * c.resolution) - if now.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) { - c.values[c.getBucket(now)] = 0 + checkPoint := now.Add(time.Duration(-1*i) * c.resolution) + if checkPoint.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) { + c.values[c.getBucket(checkPoint)] = 0 } else { break } diff --git a/memmetrics/counter_test.go b/memmetrics/counter_test.go index c03b1f6..903cb33 100644 --- a/memmetrics/counter_test.go +++ b/memmetrics/counter_test.go @@ -1,6 +1,7 @@ package memmetrics import ( + "math" "testing" "github.com/stretchr/testify/assert" @@ -27,3 +28,25 @@ func TestCloneExpired(t *testing.T) { assert.EqualValues(t, 2, out.Count()) } + +func Test_cleanup(t *testing.T) { + clock.Freeze(clock.Date(2012, 3, 4, 5, 6, 7, 0, clock.UTC)) + + cnt, err := NewCounter(10, clock.Second) + require.NoError(t, err) + + cnt.Inc(1) + + for i := 0; i < 9; i++ { + clock.Advance(clock.Second) + cnt.Inc(int(math.Pow10(i + 1))) + } + + assert.EqualValues(t, 1111111111, cnt.Count()) + assert.Equal(t, []int{1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 1, 10, 100}, cnt.values) + + clock.Advance(9 * clock.Second) + + assert.EqualValues(t, 1000000000, cnt.Count()) + assert.Equal(t, []int{0, 0, 0, 0, 0, 0, 1000000000, 0, 0, 0}, cnt.values) +}