timer_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package metrics
  2. import (
  3. "fmt"
  4. "math"
  5. "testing"
  6. "time"
  7. )
  8. func BenchmarkTimer(b *testing.B) {
  9. tm := NewTimer()
  10. b.ResetTimer()
  11. for i := 0; i < b.N; i++ {
  12. tm.Update(1)
  13. }
  14. }
  15. func TestGetOrRegisterTimer(t *testing.T) {
  16. r := NewRegistry()
  17. NewRegisteredTimer("foo", r).Update(47)
  18. if tm := GetOrRegisterTimer("foo", r); 1 != tm.Count() {
  19. t.Fatal(tm)
  20. }
  21. }
  22. func TestTimerExtremes(t *testing.T) {
  23. tm := NewTimer()
  24. tm.Update(math.MaxInt64)
  25. tm.Update(0)
  26. if stdDev := tm.StdDev(); 4.611686018427388e+18 != stdDev {
  27. t.Errorf("tm.StdDev(): 4.611686018427388e+18 != %v\n", stdDev)
  28. }
  29. }
  30. func TestTimerFunc(t *testing.T) {
  31. tm := NewTimer()
  32. tm.Time(func() { time.Sleep(50e6) })
  33. if max := tm.Max(); 45e6 > max || max > 55e6 {
  34. t.Errorf("tm.Max(): 45e6 > %v || %v > 55e6\n", max, max)
  35. }
  36. }
  37. func TestTimerZero(t *testing.T) {
  38. tm := NewTimer()
  39. if count := tm.Count(); 0 != count {
  40. t.Errorf("tm.Count(): 0 != %v\n", count)
  41. }
  42. if min := tm.Min(); 0 != min {
  43. t.Errorf("tm.Min(): 0 != %v\n", min)
  44. }
  45. if max := tm.Max(); 0 != max {
  46. t.Errorf("tm.Max(): 0 != %v\n", max)
  47. }
  48. if mean := tm.Mean(); 0.0 != mean {
  49. t.Errorf("tm.Mean(): 0.0 != %v\n", mean)
  50. }
  51. if stdDev := tm.StdDev(); 0.0 != stdDev {
  52. t.Errorf("tm.StdDev(): 0.0 != %v\n", stdDev)
  53. }
  54. ps := tm.Percentiles([]float64{0.5, 0.75, 0.99})
  55. if 0.0 != ps[0] {
  56. t.Errorf("median: 0.0 != %v\n", ps[0])
  57. }
  58. if 0.0 != ps[1] {
  59. t.Errorf("75th percentile: 0.0 != %v\n", ps[1])
  60. }
  61. if 0.0 != ps[2] {
  62. t.Errorf("99th percentile: 0.0 != %v\n", ps[2])
  63. }
  64. if rate1 := tm.Rate1(); 0.0 != rate1 {
  65. t.Errorf("tm.Rate1(): 0.0 != %v\n", rate1)
  66. }
  67. if rate5 := tm.Rate5(); 0.0 != rate5 {
  68. t.Errorf("tm.Rate5(): 0.0 != %v\n", rate5)
  69. }
  70. if rate15 := tm.Rate15(); 0.0 != rate15 {
  71. t.Errorf("tm.Rate15(): 0.0 != %v\n", rate15)
  72. }
  73. if rateMean := tm.RateMean(); 0.0 != rateMean {
  74. t.Errorf("tm.RateMean(): 0.0 != %v\n", rateMean)
  75. }
  76. }
  77. func ExampleGetOrRegisterTimer() {
  78. m := "account.create.latency"
  79. t := GetOrRegisterTimer(m, nil)
  80. t.Update(47)
  81. fmt.Println(t.Max()) // Output: 47
  82. }