Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Last active October 30, 2019 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cirocosta/9b19380ae14b1c2bf67438bb142b618a to your computer and use it in GitHub Desktop.
Save cirocosta/9b19380ae14b1c2bf67438bb142b618a to your computer and use it in GitHub Desktop.
benchmarking who's faster: checking elapsed time (in intervals) with `time.Now().Sub()`, or using a `time.Ticker`
package main_test
import (
"time"
"testing"
)
type TimeNowChecker struct {
lastTime time.Time
interval time.Duration
}
func (t *TimeNowChecker) IsElapsed() bool {
now := time.Now()
if now.Sub(t.lastTime) > t.interval {
t.lastTime = now
return true
}
return false
}
type TickerChecker struct {
ticker *time.Ticker
}
func (t *TickerChecker) IsElapsed() bool {
select {
case <-t.ticker.C:
return true
default:
}
return false
}
const interval = 50 * time.Millisecond
func BenchmarkTimeNow(b *testing.B) {
checker := TimeNowChecker{
lastTime: time.Now(),
interval: interval,
}
for n := 0; n < b.N; n++ {
checker.IsElapsed()
}
}
func BenchmarkTicker(b *testing.B) {
checker := TickerChecker{
ticker: time.NewTicker(interval),
}
for n := 0; n < b.N; n++ {
checker.IsElapsed()
}
}
go test -bench=.
goos: darwin
goarch: amd64
BenchmarkTimeNow-12 15730425 73.0 ns/op
BenchmarkTicker-12 223836266 5.31 ns/op
PASS
ok _/tmp/bb 2.980s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment