ewma.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package metrics
  2. import (
  3. "math"
  4. "sync"
  5. "sync/atomic"
  6. )
  7. // EWMAs continuously calculate an exponentially-weighted moving average
  8. // based on an outside source of clock ticks.
  9. //
  10. // This is an interface so as to encourage other structs to implement
  11. // the EWMA API as appropriate.
  12. type EWMA interface {
  13. Rate() float64
  14. Tick()
  15. Update(int64)
  16. }
  17. // The standard implementation of an EWMA tracks the number of uncounted
  18. // events and processes them on each tick. It uses the sync/atomic package
  19. // to manage uncounted events.
  20. type StandardEWMA struct {
  21. alpha float64
  22. init bool
  23. mutex sync.Mutex
  24. rate float64
  25. uncounted int64
  26. }
  27. // Force the compiler to check that StandardEWMA implements EWMA.
  28. var _ EWMA = &StandardEWMA{}
  29. // Create a new EWMA with the given alpha.
  30. func NewEWMA(alpha float64) *StandardEWMA {
  31. return &StandardEWMA{alpha: alpha}
  32. }
  33. // Create a new EWMA with alpha set for a one-minute moving average.
  34. func NewEWMA1() *StandardEWMA {
  35. return NewEWMA(1 - math.Exp(-5.0/60.0/1))
  36. }
  37. // Create a new EWMA with alpha set for a five-minute moving average.
  38. func NewEWMA5() *StandardEWMA {
  39. return NewEWMA(1 - math.Exp(-5.0/60.0/5))
  40. }
  41. // Create a new EWMA with alpha set for a fifteen-minute moving average.
  42. func NewEWMA15() *StandardEWMA {
  43. return NewEWMA(1 - math.Exp(-5.0/60.0/15))
  44. }
  45. // Return the moving average rate of events per second.
  46. func (a *StandardEWMA) Rate() float64 {
  47. a.mutex.Lock()
  48. defer a.mutex.Unlock()
  49. return a.rate * float64(1e9)
  50. }
  51. // Tick the clock to update the moving average.
  52. func (a *StandardEWMA) Tick() {
  53. count := atomic.LoadInt64(&a.uncounted)
  54. atomic.AddInt64(&a.uncounted, -count)
  55. instantRate := float64(count) / float64(5e9)
  56. a.mutex.Lock()
  57. defer a.mutex.Unlock()
  58. if a.init {
  59. a.rate += a.alpha * (instantRate - a.rate)
  60. } else {
  61. a.init = true
  62. a.rate = instantRate
  63. }
  64. }
  65. // Add n uncounted events.
  66. func (a *StandardEWMA) Update(n int64) {
  67. atomic.AddInt64(&a.uncounted, n)
  68. }