add godoc for RollingWindow (#351)

master
Kevin Wan 4 years ago committed by GitHub
parent 7a921f66e6
commit a79cee12ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -8,8 +8,10 @@ import (
) )
type ( type (
// RollingWindowOption let callers customize the RollingWindow.
RollingWindowOption func(rollingWindow *RollingWindow) RollingWindowOption func(rollingWindow *RollingWindow)
// RollingWindow defines a rolling window to calculate the events in buckets with time interval.
RollingWindow struct { RollingWindow struct {
lock sync.RWMutex lock sync.RWMutex
size int size int
@ -21,6 +23,8 @@ type (
} }
) )
// NewRollingWindow returns a RollingWindow that with size buckets and time interval,
// use opts to customize the RollingWindow.
func NewRollingWindow(size int, interval time.Duration, opts ...RollingWindowOption) *RollingWindow { func NewRollingWindow(size int, interval time.Duration, opts ...RollingWindowOption) *RollingWindow {
if size < 1 { if size < 1 {
panic("size must be greater than 0") panic("size must be greater than 0")
@ -38,6 +42,7 @@ func NewRollingWindow(size int, interval time.Duration, opts ...RollingWindowOpt
return w return w
} }
// Add adds value to current bucket.
func (rw *RollingWindow) Add(v float64) { func (rw *RollingWindow) Add(v float64) {
rw.lock.Lock() rw.lock.Lock()
defer rw.lock.Unlock() defer rw.lock.Unlock()
@ -45,6 +50,7 @@ func (rw *RollingWindow) Add(v float64) {
rw.win.add(rw.offset, v) rw.win.add(rw.offset, v)
} }
// Reduce runs fn on all buckets, ignore current bucket if ignoreCurrent was set.
func (rw *RollingWindow) Reduce(fn func(b *Bucket)) { func (rw *RollingWindow) Reduce(fn func(b *Bucket)) {
rw.lock.RLock() rw.lock.RLock()
defer rw.lock.RUnlock() defer rw.lock.RUnlock()
@ -81,7 +87,7 @@ func (rw *RollingWindow) updateOffset() {
offset := rw.offset offset := rw.offset
// reset expired buckets // reset expired buckets
for i := 0; i < span; i++ { for i := 0; i < span; i++ {
rw.win.resetBucket(offset + 1 + i) rw.win.resetBucket(offset + i + 1)
} }
rw.offset = (offset + span) % rw.size rw.offset = (offset + span) % rw.size
@ -90,6 +96,7 @@ func (rw *RollingWindow) updateOffset() {
rw.lastTime = now - (now-rw.lastTime)%rw.interval rw.lastTime = now - (now-rw.lastTime)%rw.interval
} }
// Bucket defines the bucket that holds sum and num of additions.
type Bucket struct { type Bucket struct {
Sum float64 Sum float64
Count int64 Count int64
@ -135,6 +142,7 @@ func (w *window) resetBucket(offset int) {
w.buckets[offset%w.size].reset() w.buckets[offset%w.size].reset()
} }
// IgnoreCurrentBucket lets the Reduce call ignore current bucket.
func IgnoreCurrentBucket() RollingWindowOption { func IgnoreCurrentBucket() RollingWindowOption {
return func(w *RollingWindow) { return func(w *RollingWindow) {
w.ignoreCurrent = true w.ignoreCurrent = true

Loading…
Cancel
Save