I'm playing around with benchmarks in Go and I have a simple function that just sleeps for 5 Nanoseconds, however when I run a benchmark test it shows 298.1 ns/op
. I'm curious why is that. Shouldn't it be 5 ns/op
?
Go version:
go version go1.19 linux/amd64
The code:
package andrei
import (
"testing"
"time"
)
func Hi() {
time.Sleep(5 * time.Nanosecond)
}
func BenchmarkHi(b *testing.B) {
for i := 0; i < b.N; i++ {
Hi()
}
}
The results:
$ go test -run none -bench . -benchmem ./andrei
goos: linux
goarch: amd64
pkg: andrei/andrei
cpu: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
BenchmarkHi-8 3861392 298.1 ns/op 0 B/op 0 allocs/op
PASS
ok andrei/andrei 1.470s
rdtsc
throughput on Ice Lake / Tiger Lake is about 27 cycles (uops.info), so that's about one per 5.7 ns at max turbo 4.7 GHz. But you can be sure that separatetime.Sleep
calls will need to do more than just check the current time-stamp counter once!tpause
to pause the CPU until a short deadline; that was new in Tremont and Alder Lake. And even that would need rdtsc + tpause, after checking that the sleep was too short to make a system call to let it schedule another task until we're ready to wake up. Anyway yeah, trying to sleep or delay for about 20 clock cycles isn't something that makes sense in a high-level language; you'd better be writing asm by hand for a known uarch. See also (How to calculate time for an asm delay loop on x86 linux?)