histogram_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package metrics
  2. import "testing"
  3. func BenchmarkHistogram(b *testing.B) {
  4. h := NewHistogram(NewUniformSample(100))
  5. b.ResetTimer()
  6. for i := 0; i < b.N; i++ {
  7. h.Update(int64(i))
  8. }
  9. }
  10. func TestGetOrRegisterHistogram(t *testing.T) {
  11. r := NewRegistry()
  12. s := NewUniformSample(100)
  13. NewRegisteredHistogram("foo", r, s).Update(47)
  14. if h := GetOrRegisterHistogram("foo", r, s); 1 != h.Count() {
  15. t.Fatal(h)
  16. }
  17. }
  18. func TestHistogram10000(t *testing.T) {
  19. h := NewHistogram(NewUniformSample(100000))
  20. for i := 1; i <= 10000; i++ {
  21. h.Update(int64(i))
  22. }
  23. testHistogram10000(t, h)
  24. }
  25. func TestHistogramEmpty(t *testing.T) {
  26. h := NewHistogram(NewUniformSample(100))
  27. if count := h.Count(); 0 != count {
  28. t.Errorf("h.Count(): 0 != %v\n", count)
  29. }
  30. if min := h.Min(); 0 != min {
  31. t.Errorf("h.Min(): 0 != %v\n", min)
  32. }
  33. if max := h.Max(); 0 != max {
  34. t.Errorf("h.Max(): 0 != %v\n", max)
  35. }
  36. if mean := h.Mean(); 0.0 != mean {
  37. t.Errorf("h.Mean(): 0.0 != %v\n", mean)
  38. }
  39. if stdDev := h.StdDev(); 0.0 != stdDev {
  40. t.Errorf("h.StdDev(): 0.0 != %v\n", stdDev)
  41. }
  42. ps := h.Percentiles([]float64{0.5, 0.75, 0.99})
  43. if 0.0 != ps[0] {
  44. t.Errorf("median: 0.0 != %v\n", ps[0])
  45. }
  46. if 0.0 != ps[1] {
  47. t.Errorf("75th percentile: 0.0 != %v\n", ps[1])
  48. }
  49. if 0.0 != ps[2] {
  50. t.Errorf("99th percentile: 0.0 != %v\n", ps[2])
  51. }
  52. }
  53. func TestHistogramSnapshot(t *testing.T) {
  54. h := NewHistogram(NewUniformSample(100000))
  55. for i := 1; i <= 10000; i++ {
  56. h.Update(int64(i))
  57. }
  58. snapshot := h.Snapshot()
  59. h.Update(0)
  60. testHistogram10000(t, snapshot)
  61. }
  62. func testHistogram10000(t *testing.T, h Histogram) {
  63. if count := h.Count(); 10000 != count {
  64. t.Errorf("h.Count(): 10000 != %v\n", count)
  65. }
  66. if min := h.Min(); 1 != min {
  67. t.Errorf("h.Min(): 1 != %v\n", min)
  68. }
  69. if max := h.Max(); 10000 != max {
  70. t.Errorf("h.Max(): 10000 != %v\n", max)
  71. }
  72. if mean := h.Mean(); 5000.5 != mean {
  73. t.Errorf("h.Mean(): 5000.5 != %v\n", mean)
  74. }
  75. if stdDev := h.StdDev(); 2886.751331514372 != stdDev {
  76. t.Errorf("h.StdDev(): 2886.751331514372 != %v\n", stdDev)
  77. }
  78. ps := h.Percentiles([]float64{0.5, 0.75, 0.99})
  79. if 5000.5 != ps[0] {
  80. t.Errorf("median: 5000.5 != %v\n", ps[0])
  81. }
  82. if 7500.75 != ps[1] {
  83. t.Errorf("75th percentile: 7500.75 != %v\n", ps[1])
  84. }
  85. if 9900.99 != ps[2] {
  86. t.Errorf("99th percentile: 9900.99 != %v\n", ps[2])
  87. }
  88. }