Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
```

Expand Down
3 changes: 2 additions & 1 deletion slidingwindow.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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]
Expand Down
9 changes: 9 additions & 0 deletions slidingwindow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}