github.com/loov/hrtime@v1.0.3/hrtesting/benchmark.go (about) 1 // +build !nohrtime 2 3 package hrtesting 4 5 import ( 6 "math" 7 "testing" 8 9 "github.com/loov/hrtime" 10 ) 11 12 // Benchmark wraps *testing.B to measure more details using hrtime.Benchmark 13 type Benchmark struct { 14 hr hrtime.Benchmark 15 b *testing.B 16 } 17 18 // NewBenchmark creates a new *hrtime.Benchmark using *testing.B parameters. 19 func NewBenchmark(b *testing.B) *Benchmark { 20 bench := &Benchmark{ 21 hr: *hrtime.NewBenchmark(b.N), 22 b: b, 23 } 24 bench.b.StopTimer() 25 return bench 26 } 27 28 // Next starts measuring the next lap. 29 // It will return false, when all measurements have been made. 30 func (bench *Benchmark) Next() bool { 31 bench.b.StartTimer() 32 result := bench.hr.Next() 33 if !result { 34 bench.b.StopTimer() 35 } 36 return result 37 } 38 39 // Name returns benchmark name. 40 func (bench *Benchmark) Name() string { return bench.b.Name() } 41 42 // Unit returns units it measures. 43 func (bench *Benchmark) Unit() string { return bench.hr.Unit() } 44 45 // Float64s returns all measurements. 46 func (bench *Benchmark) Float64s() []float64 { return bench.hr.Float64s() } 47 48 // BenchmarkTSC wraps *testing.B to measure more details using hrtime.BenchmarkTSC 49 type BenchmarkTSC struct { 50 hr hrtime.BenchmarkTSC 51 b *testing.B 52 } 53 54 // NewBenchmarkTSC creates a new *hrtime.BenchmarkTSC using *testing.B parameters. 55 func NewBenchmarkTSC(b *testing.B) *BenchmarkTSC { 56 bench := &BenchmarkTSC{ 57 hr: *hrtime.NewBenchmarkTSC(b.N), 58 b: b, 59 } 60 bench.b.StopTimer() 61 return bench 62 } 63 64 // Name returns benchmark name. 65 func (bench *BenchmarkTSC) Name() string { return bench.b.Name() } 66 67 // Next starts measuring the next lap. 68 // It will return false, when all measurements have been made. 69 func (bench *BenchmarkTSC) Next() bool { 70 bench.b.StartTimer() 71 result := bench.hr.Next() 72 if !result { 73 bench.b.StopTimer() 74 } 75 return result 76 } 77 78 // Unit returns units it measures. 79 func (bench *BenchmarkTSC) Unit() string { return bench.hr.Unit() } 80 81 // Float64s returns all measurements as float64s 82 func (bench *BenchmarkTSC) Float64s() []float64 { return bench.hr.Float64s() } 83 84 func truncate(v float64, digits int) float64 { 85 if digits == 0 { 86 return 0 87 } 88 89 scale := math.Pow(10, math.Floor(math.Log10(v))+1-float64(digits)) 90 return scale * math.Trunc(v/scale) 91 }