ewma.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // Create a new EWMA with the given alpha.
  18. func NewEWMA(alpha float64) EWMA {
  19. if UseNilMetrics {
  20. return NilEWMA{}
  21. }
  22. return &StandardEWMA{alpha: alpha}
  23. }
  24. // Create a new EWMA with alpha set for a one-minute moving average.
  25. func NewEWMA1() EWMA {
  26. return NewEWMA(1 - math.Exp(-5.0/60.0/1))
  27. }
  28. // Create a new EWMA with alpha set for a five-minute moving average.
  29. func NewEWMA5() EWMA {
  30. return NewEWMA(1 - math.Exp(-5.0/60.0/5))
  31. }
  32. // Create a new EWMA with alpha set for a fifteen-minute moving average.
  33. func NewEWMA15() EWMA {
  34. return NewEWMA(1 - math.Exp(-5.0/60.0/15))
  35. }
  36. // No-op EWMA.
  37. type NilEWMA struct{}
  38. // No-op.
  39. func (NilEWMA) Rate() float64 { return 0.0 }
  40. // No-op.
  41. func (NilEWMA) Tick() {}
  42. // No-op.
  43. func (NilEWMA) Update(n int64) {}
  44. // The standard implementation of an EWMA tracks the number of uncounted
  45. // events and processes them on each tick. It uses the sync/atomic package
  46. // to manage uncounted events.
  47. type StandardEWMA struct {
  48. alpha float64
  49. init bool
  50. mutex sync.Mutex
  51. rate float64
  52. uncounted int64
  53. }
  54. // Return the moving average rate of events per second.
  55. func (a *StandardEWMA) Rate() float64 {
  56. a.mutex.Lock()
  57. defer a.mutex.Unlock()
  58. return a.rate * float64(1e9)
  59. }
  60. // Tick the clock to update the moving average.
  61. func (a *StandardEWMA) Tick() {
  62. count := atomic.LoadInt64(&a.uncounted)
  63. atomic.AddInt64(&a.uncounted, -count)
  64. instantRate := float64(count) / float64(5e9)
  65. a.mutex.Lock()
  66. defer a.mutex.Unlock()
  67. if a.init {
  68. a.rate += a.alpha * (instantRate - a.rate)
  69. } else {
  70. a.init = true
  71. a.rate = instantRate
  72. }
  73. }
  74. // Add n uncounted events.
  75. func (a *StandardEWMA) Update(n int64) {
  76. atomic.AddInt64(&a.uncounted, n)
  77. }