avgcounter

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2021 License: MIT Imports: 3 Imported by: 0

README

avgcounter

Package avgcounter implements a simple EMA (Exponential Moving Average) counter. The counter holds the exponentially (by time) weighted average of all added values.

See documentation and examples at pkg.go.dev

Documentation

Overview

Package avgcounter implements a simple EMA (Exponential Moving Average) counter. The New function creates a counter with the only parameter: avgInterval. Every Add call adds the value to the counter. The current value can be obtained using the Value method.

The counter holds the exponentially (by time) weighted average of all added values.

Example
counter := New(time.Minute)
counter.Add(42)

// We use special function in the test to emulate time passing. You don't
// need to do that, just let time fly.
passTime(time.Minute)

// The result is 42 * exp(-1)
fmt.Println(counter.Value())
Output:

15.450936529200579
Example (Multi_add)
counter := New(time.Minute)

for i := 0; i < 600; i++ {
	counter.Add(1)
	passTime(time.Second)
}

// The result about 60 (60 adds/minute)
fmt.Println(counter.Value())
Output:

59.49868752358285

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Counter

type Counter struct {
	// contains filtered or unexported fields
}

Counter is an EMA (Exponential Moving Average) counter.

func New

func New(avgInterval time.Duration) *Counter

New creates a new Counter with the given avgInterval.

Example
counter := New(time.Minute)

fmt.Println(counter.Value())
Output:

0

func (*Counter) Add

func (c *Counter) Add(v float64)

Add adds a new value to the counter.

Example
counter := New(time.Minute)
counter.Add(42)

fmt.Println(counter.Value())
Output:

42
Example (More)
counter := New(time.Minute)
counter.Add(42)

passTime(2 * time.Minute)
counter.Add(42)

// The result is 42 + 42 * exp(-2)
fmt.Println(counter.Value())
Output:

47.68408189593774

func (*Counter) Value

func (c *Counter) Value() float64

Value returns the current value of the counter.

func (*Counter) ValuePer

func (c *Counter) ValuePer(interval time.Duration) float64

ValuePer returns the current value of the counter, normalized to the given interval. It is actually a Value() * interval / avgInterval.

Example
counter := New(time.Minute)
counter.Add(42)

// 42 per minute is the 0.7 per second
fmt.Println(counter.ValuePer(time.Second))
Output:

0.7

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL