timer_metrics.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package timer_metrics
  2. import (
  3. "fmt"
  4. "log"
  5. "math"
  6. "sort"
  7. "sync"
  8. "time"
  9. )
  10. type TimerMetrics struct {
  11. sync.Mutex
  12. timings durations
  13. prefix string
  14. statusEvery int
  15. position int
  16. }
  17. // start a new TimerMetrics to print out metrics every n times
  18. func NewTimerMetrics(statusEvery int, prefix string) *TimerMetrics {
  19. s := &TimerMetrics{
  20. statusEvery: statusEvery,
  21. prefix: prefix,
  22. }
  23. if statusEvery > 0 {
  24. if statusEvery < 100 {
  25. log.Printf("Warning: use more than 100 status values for accurate percentiles (configured with %d)", statusEvery)
  26. }
  27. s.timings = make(durations, 0, statusEvery)
  28. }
  29. return s
  30. }
  31. type durations []time.Duration
  32. func (s durations) Len() int { return len(s) }
  33. func (s durations) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  34. func (s durations) Less(i, j int) bool { return s[i] < s[j] }
  35. func percentile(perc float64, arr durations) time.Duration {
  36. length := len(arr)
  37. if length == 0 {
  38. return 0
  39. }
  40. indexOfPerc := int(math.Ceil(((perc / 100.0) * float64(length)) + 0.5))
  41. if indexOfPerc >= length {
  42. indexOfPerc = length - 1
  43. }
  44. return arr[indexOfPerc]
  45. }
  46. type Stats struct {
  47. Prefix string
  48. Count int
  49. Avg time.Duration
  50. P95 time.Duration
  51. P99 time.Duration
  52. }
  53. func (s *Stats) String() string {
  54. p95Ms := s.P95.Seconds() * 1000
  55. p99Ms := s.P99.Seconds() * 1000
  56. avgMs := s.Avg.Seconds() * 1000
  57. return fmt.Sprintf("%s finished %d - 99th: %.02fms - 95th: %.02fms - avg: %.02fms",
  58. s.Prefix, s.Count, p99Ms, p95Ms, avgMs)
  59. }
  60. func (m *TimerMetrics) getStats() *Stats {
  61. var total time.Duration
  62. for _, v := range m.timings {
  63. total += v
  64. }
  65. // make a copy of timings so we still rotate through in order
  66. timings := make(durations, len(m.timings))
  67. copy(timings, m.timings)
  68. sort.Sort(timings)
  69. var avg time.Duration
  70. if len(timings) > 0 {
  71. avg = total / time.Duration(len(m.timings))
  72. }
  73. return &Stats{
  74. Prefix: m.prefix,
  75. Count: len(m.timings),
  76. Avg: avg,
  77. P95: percentile(95.0, timings),
  78. P99: percentile(99.0, timings),
  79. }
  80. }
  81. // get the current Stats
  82. func (m *TimerMetrics) Stats() *Stats {
  83. m.Lock()
  84. s := m.getStats()
  85. m.Unlock()
  86. return s
  87. }
  88. // record a delta from time.Now()
  89. func (m *TimerMetrics) Status(startTime time.Time) {
  90. if m.statusEvery == 0 {
  91. return
  92. }
  93. m.StatusDuration(time.Now().Sub(startTime))
  94. }
  95. // Record a duration, printing out stats every statusEvery interval
  96. func (m *TimerMetrics) StatusDuration(duration time.Duration) {
  97. if m.statusEvery == 0 {
  98. return
  99. }
  100. m.Lock()
  101. m.position++
  102. var looped bool
  103. if m.position > m.statusEvery {
  104. // loop back around
  105. looped = true
  106. m.position = 1
  107. }
  108. if m.position > len(m.timings) {
  109. m.timings = append(m.timings, duration)
  110. } else {
  111. m.timings[m.position-1] = duration
  112. }
  113. if !looped {
  114. m.Unlock()
  115. return
  116. }
  117. stats := m.getStats()
  118. m.Unlock()
  119. log.Printf("%s", stats)
  120. }