ewma.go 2.1 KB

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