github.com/zeebo/mon@v0.0.0-20211012163247-13d39bdb54fa/time_test.go (about) 1 package mon 2 3 import ( 4 "errors" 5 "testing" 6 7 "github.com/zeebo/assert" 8 "github.com/zeebo/this" 9 ) 10 11 func TestTime(t *testing.T) { 12 t.Run("Basic", func(t *testing.T) { 13 StartNamed("foo").Stop(nil) 14 15 Times(func(name string, his *State) bool { 16 assert.Equal(t, name, "foo") 17 assert.Equal(t, his.Total(), 1) 18 return true 19 }) 20 21 StartNamed("foo").Stop(nil) 22 23 Times(func(name string, his *State) bool { 24 assert.Equal(t, name, "foo") 25 assert.Equal(t, his.Total(), 2) 26 return true 27 }) 28 29 StartNamed("bar").Stop(nil) 30 31 Times(func(name string, his *State) bool { 32 switch name { 33 case "foo": 34 assert.Equal(t, his.Total(), 2) 35 case "bar": 36 assert.Equal(t, his.Total(), 1) 37 default: 38 t.Fatal("invalid name:", name) 39 } 40 return true 41 }) 42 43 Collect(func(name string, his *State) bool { return true }) 44 45 Collect(func(_ string, _ *State) bool { 46 assert.That(t, false) 47 return true 48 }) 49 }) 50 } 51 52 func BenchmarkNanotime(b *testing.B) { 53 for i := 0; i < b.N; i++ { 54 _ = nanotime() 55 } 56 } 57 58 func BenchmarkTime(b *testing.B) { 59 b.Run("Auto", func(b *testing.B) { 60 b.ReportAllocs() 61 62 for i := 0; i < b.N; i++ { 63 func() { 64 timer := Start() 65 defer timer.Stop(nil) 66 }() 67 } 68 }) 69 70 b.Run("This", func(b *testing.B) { 71 b.ReportAllocs() 72 73 for i := 0; i < b.N; i++ { 74 func() { 75 timer := StartNamed(this.This()) 76 defer timer.Stop(nil) 77 }() 78 } 79 }) 80 81 b.Run("Named", func(b *testing.B) { 82 b.ReportAllocs() 83 84 for i := 0; i < b.N; i++ { 85 func() { 86 timer := StartNamed("bench") 87 defer timer.Stop(nil) 88 }() 89 } 90 }) 91 92 b.Run("Thunk", func(b *testing.B) { 93 b.ReportAllocs() 94 var thunk Thunk 95 96 for i := 0; i < b.N; i++ { 97 func() { 98 timer := thunk.Start() 99 defer timer.Stop(nil) 100 }() 101 } 102 }) 103 104 b.Run("WithError", func(b *testing.B) { 105 err := errors.New("some error: whatever") 106 b.ReportAllocs() 107 108 for i := 0; i < b.N; i++ { 109 func() { 110 timer := Start() 111 defer timer.Stop(&err) 112 }() 113 } 114 }) 115 }