github.com/phillinzzz/newBsc@v1.1.6/metrics/timer_test.go (about) 1 package metrics 2 3 import ( 4 "fmt" 5 "math" 6 "testing" 7 "time" 8 ) 9 10 func BenchmarkTimer(b *testing.B) { 11 tm := NewTimer() 12 b.ResetTimer() 13 for i := 0; i < b.N; i++ { 14 tm.Update(1) 15 } 16 } 17 18 func TestGetOrRegisterTimer(t *testing.T) { 19 r := NewRegistry() 20 NewRegisteredTimer("foo", r).Update(47) 21 if tm := GetOrRegisterTimer("foo", r); tm.Count() != 1 { 22 t.Fatal(tm) 23 } 24 } 25 26 func TestTimerExtremes(t *testing.T) { 27 tm := NewTimer() 28 tm.Update(math.MaxInt64) 29 tm.Update(0) 30 if stdDev := tm.StdDev(); stdDev != 4.611686018427388e+18 { 31 t.Errorf("tm.StdDev(): 4.611686018427388e+18 != %v\n", stdDev) 32 } 33 } 34 35 func TestTimerStop(t *testing.T) { 36 l := len(arbiter.meters) 37 tm := NewTimer() 38 if l+1 != len(arbiter.meters) { 39 t.Errorf("arbiter.meters: %d != %d\n", l+1, len(arbiter.meters)) 40 } 41 tm.Stop() 42 if l != len(arbiter.meters) { 43 t.Errorf("arbiter.meters: %d != %d\n", l, len(arbiter.meters)) 44 } 45 } 46 47 func TestTimerFunc(t *testing.T) { 48 var ( 49 tm = NewTimer() 50 testStart = time.Now() 51 actualTime time.Duration 52 ) 53 tm.Time(func() { 54 time.Sleep(50 * time.Millisecond) 55 actualTime = time.Since(testStart) 56 }) 57 var ( 58 drift = time.Millisecond * 2 59 measured = time.Duration(tm.Max()) 60 ceil = actualTime + drift 61 floor = actualTime - drift 62 ) 63 if measured > ceil || measured < floor { 64 t.Errorf("tm.Max(): %v > %v || %v > %v\n", measured, ceil, measured, floor) 65 } 66 } 67 68 func TestTimerZero(t *testing.T) { 69 tm := NewTimer() 70 if count := tm.Count(); count != 0 { 71 t.Errorf("tm.Count(): 0 != %v\n", count) 72 } 73 if min := tm.Min(); min != 0 { 74 t.Errorf("tm.Min(): 0 != %v\n", min) 75 } 76 if max := tm.Max(); max != 0 { 77 t.Errorf("tm.Max(): 0 != %v\n", max) 78 } 79 if mean := tm.Mean(); mean != 0.0 { 80 t.Errorf("tm.Mean(): 0.0 != %v\n", mean) 81 } 82 if stdDev := tm.StdDev(); stdDev != 0.0 { 83 t.Errorf("tm.StdDev(): 0.0 != %v\n", stdDev) 84 } 85 ps := tm.Percentiles([]float64{0.5, 0.75, 0.99}) 86 if ps[0] != 0.0 { 87 t.Errorf("median: 0.0 != %v\n", ps[0]) 88 } 89 if ps[1] != 0.0 { 90 t.Errorf("75th percentile: 0.0 != %v\n", ps[1]) 91 } 92 if ps[2] != 0.0 { 93 t.Errorf("99th percentile: 0.0 != %v\n", ps[2]) 94 } 95 if rate1 := tm.Rate1(); rate1 != 0.0 { 96 t.Errorf("tm.Rate1(): 0.0 != %v\n", rate1) 97 } 98 if rate5 := tm.Rate5(); rate5 != 0.0 { 99 t.Errorf("tm.Rate5(): 0.0 != %v\n", rate5) 100 } 101 if rate15 := tm.Rate15(); rate15 != 0.0 { 102 t.Errorf("tm.Rate15(): 0.0 != %v\n", rate15) 103 } 104 if rateMean := tm.RateMean(); rateMean != 0.0 { 105 t.Errorf("tm.RateMean(): 0.0 != %v\n", rateMean) 106 } 107 } 108 109 func ExampleGetOrRegisterTimer() { 110 m := "account.create.latency" 111 t := GetOrRegisterTimer(m, nil) 112 t.Update(47) 113 fmt.Println(t.Max()) // Output: 47 114 }