go.mway.dev/chrono@v0.6.1-0.20240126030049-189c5aef20d2/clock/throttled_clock_benchmark_test.go (about) 1 // Copyright (c) 2023 Matt Way 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to 5 // deal in the Software without restriction, including without limitation the 6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 // sell copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 // IN THE THE SOFTWARE. 20 21 package clock_test 22 23 import ( 24 "testing" 25 "time" 26 27 "go.mway.dev/chrono/clock" 28 ) 29 30 func BenchmarkThrottledClock(b *testing.B) { 31 var ( 32 cases = []struct { 33 name string 34 nowfn clock.NanotimeFunc 35 }{ 36 { 37 name: "mono", 38 nowfn: clock.DefaultNanotimeFunc(), 39 }, 40 { 41 name: "wall", 42 nowfn: clock.DefaultWallNanotimeFunc(), 43 }, 44 } 45 intervals = []time.Duration{ 46 time.Second, 47 100 * time.Millisecond, 48 10 * time.Millisecond, 49 time.Millisecond, 50 100 * time.Microsecond, 51 10 * time.Microsecond, 52 time.Microsecond, 53 } 54 nanos int64 55 ) 56 57 for _, tt := range cases { 58 b.Run(tt.name, func(b *testing.B) { 59 for _, dur := range intervals { 60 b.Run(dur.String(), func(b *testing.B) { 61 clk := clock.NewThrottledClock(tt.nowfn, dur) 62 defer clk.Stop() 63 64 b.ReportAllocs() 65 b.ResetTimer() 66 67 for i := 0; i < b.N; i++ { 68 nanos = clk.Nanotime() 69 } 70 }) 71 } 72 }) 73 } 74 75 _ = nanos 76 } 77 78 func BenchmarkThrottledClockSources(b *testing.B) { 79 var ( 80 nanos int64 81 now time.Time 82 ) 83 84 b.Run("nanos", func(b *testing.B) { 85 clk := clock.NewThrottledMonotonicClock(time.Microsecond) 86 defer clk.Stop() 87 88 b.ReportAllocs() 89 b.ResetTimer() 90 91 for i := 0; i < b.N; i++ { 92 nanos = clk.Nanotime() 93 } 94 }) 95 96 b.Run("now", func(b *testing.B) { 97 clk := clock.NewThrottledMonotonicClock(time.Microsecond) 98 defer clk.Stop() 99 100 b.ReportAllocs() 101 b.ResetTimer() 102 103 for i := 0; i < b.N; i++ { 104 now = clk.Now() 105 } 106 }) 107 108 _ = nanos 109 _ = now 110 }