timer.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package metrics
  2. import "time"
  3. type Timer interface {
  4. Count() int64
  5. Max() int64
  6. Mean() float64
  7. Min() int64
  8. Percentile(float64) float64
  9. Percentiles([]float64) []float64
  10. Rate1() float64
  11. Rate5() float64
  12. Rate15() float64
  13. RateMean() float64
  14. StdDev() float64
  15. Time(func())
  16. Update(uint64)
  17. }
  18. type timer struct {
  19. h Histogram
  20. m Meter
  21. }
  22. func NewCustomTimer(h Histogram, m Meter) Timer {
  23. return &timer{h, m}
  24. }
  25. func NewTimer() Timer {
  26. return &timer{NewHistogram(NewExpDecaySample(1028, 0.015)), NewMeter()}
  27. }
  28. func (t *timer) Count() int64 {
  29. return t.h.Count()
  30. }
  31. func (t *timer) Max() int64 {
  32. return t.h.Max()
  33. }
  34. func (t *timer) Mean() float64 {
  35. return t.h.Mean()
  36. }
  37. func (t *timer) Min() int64 {
  38. return t.h.Min()
  39. }
  40. func (t *timer) Percentile(p float64) float64 {
  41. return t.h.Percentile(p)
  42. }
  43. func (t *timer) Percentiles(ps []float64) []float64 {
  44. return t.h.Percentiles(ps)
  45. }
  46. func (t *timer) Rate1() float64 {
  47. return t.m.Rate1()
  48. }
  49. func (t *timer) Rate5() float64 {
  50. return t.m.Rate5()
  51. }
  52. func (t *timer) Rate15() float64 {
  53. return t.m.Rate15()
  54. }
  55. func (t *timer) RateMean() float64 {
  56. return t.m.RateMean()
  57. }
  58. func (t *timer) StdDev() float64 {
  59. return t.h.StdDev()
  60. }
  61. func (t *timer) Time(f func()) {
  62. ts := time.Nanoseconds()
  63. f()
  64. t.Update(uint64(time.Nanoseconds() - ts))
  65. }
  66. func (t *timer) Update(duration uint64) {
  67. t.h.Update(int64(duration))
  68. t.m.Mark(1)
  69. }