github.com/luckypickle/go-ethereum-vet@v1.14.2/metrics/metrics_test.go (about) 1 package metrics 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "log" 7 "sync" 8 "testing" 9 "time" 10 ) 11 12 const FANOUT = 128 13 14 // Stop the compiler from complaining during debugging. 15 var ( 16 _ = ioutil.Discard 17 _ = log.LstdFlags 18 ) 19 20 func BenchmarkMetrics(b *testing.B) { 21 r := NewRegistry() 22 c := NewRegisteredCounter("counter", r) 23 g := NewRegisteredGauge("gauge", r) 24 gf := NewRegisteredGaugeFloat64("gaugefloat64", r) 25 h := NewRegisteredHistogram("histogram", r, NewUniformSample(100)) 26 m := NewRegisteredMeter("meter", r) 27 t := NewRegisteredTimer("timer", r) 28 RegisterDebugGCStats(r) 29 RegisterRuntimeMemStats(r) 30 b.ResetTimer() 31 ch := make(chan bool) 32 33 wgD := &sync.WaitGroup{} 34 /* 35 wgD.Add(1) 36 go func() { 37 defer wgD.Done() 38 //log.Println("go CaptureDebugGCStats") 39 for { 40 select { 41 case <-ch: 42 //log.Println("done CaptureDebugGCStats") 43 return 44 default: 45 CaptureDebugGCStatsOnce(r) 46 } 47 } 48 }() 49 //*/ 50 51 wgR := &sync.WaitGroup{} 52 //* 53 wgR.Add(1) 54 go func() { 55 defer wgR.Done() 56 //log.Println("go CaptureRuntimeMemStats") 57 for { 58 select { 59 case <-ch: 60 //log.Println("done CaptureRuntimeMemStats") 61 return 62 default: 63 CaptureRuntimeMemStatsOnce(r) 64 } 65 } 66 }() 67 //*/ 68 69 wgW := &sync.WaitGroup{} 70 /* 71 wgW.Add(1) 72 go func() { 73 defer wgW.Done() 74 //log.Println("go Write") 75 for { 76 select { 77 case <-ch: 78 //log.Println("done Write") 79 return 80 default: 81 WriteOnce(r, ioutil.Discard) 82 } 83 } 84 }() 85 //*/ 86 87 wg := &sync.WaitGroup{} 88 wg.Add(FANOUT) 89 for i := 0; i < FANOUT; i++ { 90 go func(i int) { 91 defer wg.Done() 92 //log.Println("go", i) 93 for i := 0; i < b.N; i++ { 94 c.Inc(1) 95 g.Update(int64(i)) 96 gf.Update(float64(i)) 97 h.Update(int64(i)) 98 m.Mark(1) 99 t.Update(1) 100 } 101 //log.Println("done", i) 102 }(i) 103 } 104 wg.Wait() 105 close(ch) 106 wgD.Wait() 107 wgR.Wait() 108 wgW.Wait() 109 } 110 111 func Example() { 112 c := NewCounter() 113 Register("money", c) 114 c.Inc(17) 115 116 // Threadsafe registration 117 t := GetOrRegisterTimer("db.get.latency", nil) 118 t.Time(func() { time.Sleep(10 * time.Millisecond) }) 119 t.Update(1) 120 121 fmt.Println(c.Count()) 122 fmt.Println(t.Min()) 123 // Output: 17 124 // 1 125 }