Skip to content

Commit

Permalink
add godoc for RollingWindow (zeromicro#351)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan authored Jan 4, 2021
1 parent 7a921f6 commit a79cee1
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion core/collection/rollingwindow.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import (
)

type (
// RollingWindowOption let callers customize the RollingWindow.
RollingWindowOption func(rollingWindow *RollingWindow)

// RollingWindow defines a rolling window to calculate the events in buckets with time interval.
RollingWindow struct {
lock sync.RWMutex
size int
Expand All @@ -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 {
if size < 1 {
panic("size must be greater than 0")
Expand All @@ -38,13 +42,15 @@ func NewRollingWindow(size int, interval time.Duration, opts ...RollingWindowOpt
return w
}

// Add adds value to current bucket.
func (rw *RollingWindow) Add(v float64) {
rw.lock.Lock()
defer rw.lock.Unlock()
rw.updateOffset()
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)) {
rw.lock.RLock()
defer rw.lock.RUnlock()
Expand Down Expand Up @@ -81,7 +87,7 @@ func (rw *RollingWindow) updateOffset() {
offset := rw.offset
// reset expired buckets
for i := 0; i < span; i++ {
rw.win.resetBucket(offset + 1 + i)
rw.win.resetBucket(offset + i + 1)
}

rw.offset = (offset + span) % rw.size
Expand All @@ -90,6 +96,7 @@ func (rw *RollingWindow) updateOffset() {
rw.lastTime = now - (now-rw.lastTime)%rw.interval
}

// Bucket defines the bucket that holds sum and num of additions.
type Bucket struct {
Sum float64
Count int64
Expand Down Expand Up @@ -135,6 +142,7 @@ func (w *window) resetBucket(offset int) {
w.buckets[offset%w.size].reset()
}

// IgnoreCurrentBucket lets the Reduce call ignore current bucket.
func IgnoreCurrentBucket() RollingWindowOption {
return func(w *RollingWindow) {
w.ignoreCurrent = true
Expand Down

0 comments on commit a79cee1

Please sign in to comment.