Skip to content

Instantly share code, notes, and snippets.

@artyom
Created February 6, 2024 11:14
Show Gist options
  • Save artyom/5e5482db9ac4f5f3c53e5a83ab652577 to your computer and use it in GitHub Desktop.
Save artyom/5e5482db9ac4f5f3c53e5a83ab652577 to your computer and use it in GitHub Desktop.
rate.Sometimes vs time.Ticker
goos: darwin
goarch: arm64
pkg: ids-rewrite-experiment
BenchmarkSometimes/ticker-8 387814022 2.915 ns/op
BenchmarkSometimes/sometimes-8 44387656 27.03 ns/op
var sink int
func BenchmarkSometimes(b *testing.B) {
fn := func() { sink++ }
b.Run("ticker", func(b *testing.B) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for i := 0; i < b.N; i++ {
if i == 0 {
fn()
} else {
select {
case <-ticker.C:
fn()
default:
}
}
}
})
b.Run("sometimes", func(b *testing.B) {
s := rate.Sometimes{First: 1, Interval: time.Second}
for i := 0; i < b.N; i++ {
s.Do(fn)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment