Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save optix2000/c846af54f487358ca553945dd25b763e to your computer and use it in GitHub Desktop.
Save optix2000/c846af54f487358ca553945dd25b763e to your computer and use it in GitHub Desktop.
Golang cancellable sleep benchmarks
% go test -bench=.
goos: linux
goarch: amd64
pkg: test
cpu: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
BenchmarkCancelContext-8 345220 3498 ns/op 192 B/op 4 allocs/op
BenchmarkCancelAfter-8 765330 2659 ns/op 328 B/op 5 allocs/op
BenchmarkTimeoutContext-8 142429 9855 ns/op 480 B/op 7 allocs/op
BenchmarkTimeoutAfter-8 61796 19571 ns/op 376 B/op 6 allocs/op
PASS
ok test 8.302s
go test -bench=. 9.58s user 5.70s system 167% cpu 9.130 total
package sleeptest
import (
"context"
"time"
)
func ContextSleep(ctx context.Context, sleep time.Duration) {
c, cancel := context.WithTimeout(ctx, sleep)
<-c.Done()
cancel()
}
func AfterSleep(ctx context.Context, sleep time.Duration) {
select {
case <-ctx.Done():
case <-time.After(sleep):
}
}
package sleeptest
import (
"context"
"testing"
"time"
)
func BenchmarkCancelContext(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
ctx, cancel := context.WithCancel(context.Background())
cancel()
ContextSleep(ctx, time.Hour)
}
}
func BenchmarkCancelAfter(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
ctx, cancel := context.WithCancel(context.Background())
cancel()
AfterSleep(ctx, time.Hour)
}
}
func BenchmarkTimeoutContext(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
ctx, cancel := context.WithCancel(context.Background())
ContextSleep(ctx, 0)
cancel()
}
}
func BenchmarkTimeoutAfter(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
ctx, cancel := context.WithCancel(context.Background())
AfterSleep(ctx, 0)
cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment