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