Benchmark function
- Go course
- Intermediate
- Lesson 47/80
- 4 min
Learn the func BenchmarkXxx signature and go test -bench.
Benchmark functions
Benchmarks live in a _test.go file, start with Benchmark and take a *testing.B. The measured code runs b.N times; Go raises b.N automatically until the measurement is reliable.
func BenchmarkBirlestir(b *testing.B) {
for i := 0; i < b.N; i++ {
strings.Join([]string{"a", "b", "c"}, ",")
}
}Run: go test -bench=. -benchmem → BenchmarkBirlestir-8 25000000 48 ns/op 16 B/op 1 allocs/op
Not fooling the compiler
A computation whose result is never used can be removed by the compiler, so the benchmark measures nothing. Assign the result to a package-level variable:
var sink string
func BenchmarkX(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = strings.Repeat("a", 10)
}
}Since Go 1.24 the for b.Loop() { ... } form solves this problem and the timer handling by itself.
Practice First benchmark
Run a benchmark with testing.Benchmark that calls fmt.Sprintf("%d", i); assign the result to a sink variable. Print whether the result's N is greater than 0.
Starter code
package main
import (
"fmt"
"testing"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"testing"
)
var sink string
func main() {
r := testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = fmt.Sprintf("%d", i)
}
})
fmt.Println(r.N > 0)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the <code>-8</code> suffix in the output show?
- The iteration count
- The allocation count
- The Go version
- The GOMAXPROCS value Correct answer
Explanation: The number at the end of the benchmark name says how many Ps the measurement used; -cpu=1,4 tries different values.
2 Iteration count
for i := 0; i < b.____; i++ {
sink = hesapla()
}
for i := 0; i < b.N; i++ {
sink = hesapla()
}
Explanation: b.N is the iteration count Go picks for the measurement.
3 Output column
| Term | Meaning |
|---|---|
ns/op |
Time per operation |
B/op |
Bytes per operation |
allocs/op |
Allocations per operation |
-8 |
GOMAXPROCS |