Summary - Benchmark
- Go course
- Intermediate
- Lesson 52/80
- 4 min
Write a slice benchmark with b.Run and b.ReportAllocs.
Benchmark summary
The flow: write BenchmarkXxx(b *testing.B) → assign the result to sink → keep setup out with b.ResetTimer() → see allocations with -benchmem → split by size with b.Run → compare with -count=10 + benchstat. Take a profile with -cpuprofile if needed.
Remember: a benchmark is interpreted together with profiles and real production measurements, not on its own.
RunParallel
To measure how a concurrently used structure (a cache, a pool) behaves under real load:
func BenchmarkOnbellek(b *testing.B) {
o := yeniOnbellek()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
o.Al("anahtar")
}
})
}Running with -cpu=1,2,4,8 immediately reveals code that doesn't scale (gets slower as cores increase).
Practice Parallel benchmark
Run, with testing.Benchmark, a benchmark that increments an atomic.Int64 counter inside b.RunParallel with a pb.Next() loop. Print whether the counter is greater than 0.
Starter code
package main
import (
"fmt"
"sync/atomic"
"testing"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"sync/atomic"
"testing"
)
func main() {
var sayac atomic.Int64
testing.Benchmark(func(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sayac.Add(1)
}
})
})
fmt.Println(sayac.Load() > 0)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method measures parallel performance?
- b.Loop
- b.Parallel
- b.RunParallel Correct answer
- b.Run
Explanation: RunParallel spreads the work over GOMAXPROCS goroutines, exposing concurrency costs such as lock contention.
2 Parallel loop
b.RunParallel(func(pb *testing.PB) {
for pb.____() {
isle()
}
})
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
isle()
}
})
Explanation: pb.Next gives each goroutine the next iteration and returns false when they are used up.
3 Group summary
| Term | Meaning |
|---|---|
b.N |
Iteration count |
b.ResetTimer |
Exclude setup |
b.Run |
Sub-measurement |
b.RunParallel |
Concurrent load |