Last active
October 30, 2019 12:36
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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