diff --git a/README.md b/README.md index 60dbcc5..c21f101 100644 --- a/README.md +++ b/README.md @@ -17,23 +17,24 @@ import ( func main() { // Create a SlidingWindow that has a window of 15 minutes, with a - // granulity of 1 minute. - sw := average.MustNew(15 * time.Minute, time.Minute) + // granularity of 1 minute. + sw := average.MustNew(15*time.Second, time.Second) defer sw.Stop() - // Do some work. sw.Add(15) // Do some more work. + time.Sleep(time.Second) sw.Add(22) // Do even more work. + time.Sleep(2 * time.Second) sw.Add(22) - fmt.Printf("Average of last 1m: %f\n", sw.Average(time.Minute) - fmt.Printf("Average of last 5m: %f\n", sw.Average(5 * time.Minute) - fmt.Printf("Average of last 15m: %f\n\n", sw.Average(15 * time.Minute) + fmt.Printf("Average of last 1s: %f\n", sw.Average(time.Second)) + fmt.Printf("Average of last 2s: %f\n", sw.Average(2*time.Second)) + fmt.Printf("Average of last 15s: %f\n\n", sw.Average(15*time.Second)) - total, numSamples := sw.Total(15 * time.Minute) - fmt.Printf("Counter has a total of %d over %d samples", total, numSamples) + total, numSamples := sw.Total(15 * time.Second) + fmt.Printf("Counter has a total of %d over %d samples\n", total, numSamples) } ``` diff --git a/slidingwindow.go b/slidingwindow.go index 793422d..821e2ec 100644 --- a/slidingwindow.go +++ b/slidingwindow.go @@ -48,6 +48,7 @@ func New(window, granularity time.Duration) (*SlidingWindow, error) { granularity: granularity, samples: make([]int64, int(window/granularity)), stopC: make(chan struct{}), + size: 1, } go sw.shifter() @@ -132,7 +133,7 @@ func (sw *SlidingWindow) Total(window time.Duration) (int64, int) { for i := 1; i <= sampleCount; i++ { pos := sw.pos - i if pos < 0 { - pos += len(sw.samples) + pos += sw.size } total += sw.samples[pos] diff --git a/slidingwindow_test.go b/slidingwindow_test.go index 61abccd..082be9c 100644 --- a/slidingwindow_test.go +++ b/slidingwindow_test.go @@ -131,3 +131,12 @@ func TestTotal(t *testing.T) { t.Errorf("expected the total over the last 10 seconds to be 12, not %d", v) } } + +func TestTotalFromNew(t *testing.T) { + sw, _ := New(time.Minute, 15*time.Second) + + sw.Add(15) + if v, _ := sw.Total(time.Minute); v != 15 { + t.Errorf("expected total to be 15, but got %d", v) + } +}