name: benchmark-go description: Write Go benchmarks using testing.B and benchstat. Use when: user wants to benchmark Go code, measure performance, optimize Go programs, or compare implementations using Go's built-in benchmarking. license: MIT
Go Benchmarking
This skill covers benchmarking Go code using the built-in testing package and related tools.
Writing Benchmarks
Basic Benchmark
package main
import "testing"
func Fibonacci(n int) int {
if n < 2 {
return n
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
func BenchmarkFibonacci(b *testing.B) {
var result int
for i := 0; i < b.N; i++ {
result = Fibonacci(20)
}
// Prevent DCE
if result == 0 {
b.Fatal("unexpected")
}
}
Using b.N
The b.N value grows automatically until timing stabilizes:
func BenchmarkWork(b *testing.B) {
for i := 0; i < b.N; i++ {
doWork()
}
}
Sub-Benchmarks (Parameterized)
func BenchmarkFibonacci(b *testing.B) {
for n := 10; n <= 40; n += 10 {
b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
for i := 0; i < b.N; i++ {
Fibonacci(n)
}
})
}
}
Setup and Teardown
func BenchmarkComplex(b *testing.B) {
// Run once before timer starts
data := prepareData()
// Reset timer for actual benchmark
b.ResetTimer()
for i := 0; i < b.N; i++ {
process(data)
}
}
func BenchmarkWithPause(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer() // Pause timing
setupExpensiveState()
b.StartTimer() // Resume timing
doWork()
}
}
Running Benchmarks
Basic
go test -bench=. -benchmem
Common Flags
| Flag | Description |
|---|---|
-bench=. |
Run all benchmarks |
-benchtime=10s |
Run each benchmark for 10s |
-benchtime=100x |
Run each benchmark 100 times |
-benchmem |
Show memory allocation stats |
-count=5 |
Run each benchmark 5 times |
-run=^$ |
Don't run tests, only benchmarks |
-cpu=1,2,4 |
Run with different GOMAXPROCS |
Examples
# Run with memory stats
go test -bench=. -benchmem -count=5
# Run for 10 seconds per benchmark
go test -bench=. -benchtime=10s
# Run specific benchmark
go test -bench=Fibonacci -benchmem
# Run with CPU profile
go test -bench=. -cpuprofile=cpu.prof -memprofile=mem.prof
Output Example
BenchmarkFibonacci-8 200000 9512 ns/op 0 B/op 0 allocs/op
Format: name iterations time_per_op memory_allocations
Statistical Comparison: benchstat
Install
go install golang.org/x/perf/cmd/benchstat@latest
Usage
# Run baseline
go test -bench=. -count=10 > before.txt
# Make changes...
# Run new version
go test -bench=. -count=10 > after.txt
# Compare
benchstat before.txt after.txt
Output
name old time/op new time/op delta
Fibonacci-8 9.51us ± 2% 8.21us ± 3% -13.66% (p=0.001 significant)
Preventing Optimizations
runtime.KeepAlive
func BenchmarkWork(b *testing.B) {
var result int
for i := 0; i < b.N; i++ {
result = doWork()
}
runtime.KeepAlive(result)
}
Global Assignment
var sink int
func BenchmarkWork(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = doWork()
}
}
Report Allocations
func BenchmarkAlloc(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
allocateStuff()
}
}
Output: 1234 B/op 12 allocs/op
Profiling Go
pprof
# CPU profile
go test -bench=. -cpuprofile=cpu.prof
go tool pprof cpu.prof
# Memory profile
go test -bench=. -memprofile=mem.prof
go tool pprof mem.prof
Interactive pprof Commands
(pprof) top # Top functions by time
(pprof) top -lines # Show source lines
(pprof) list func # Profile specific function
(pprof) web # Generate SVG call graph
(pprof) web # Open in browser
(pprof) png # Save as PNG
Web Interface
# Start web UI
go tool pprof -http=:8080 cpu.prof
Opens browser with flamegraph, call graph, top list views.
Profiling Running Service
import (
_ "net/http/pprof"
"net/http"
)
func main() {
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
}
# Then profile
go tool pprof http://localhost:6060/debug/pprof/profile
Common Pitfalls
- Always use
-run=^$- Prevents tests from running with benchmarks - Use -benchtime - Default may be too short for accurate measurements
- Run with -count - Multiple runs reveal variance
- Use benchstat - Compare statistically, don't eyeball
- Warmup - Go's JIT warms up automatically, but first run may be slow
- Inlining - Small functions may be inlined; benchmark what matters
Quick Reference
| Task | Command |
|---|---|
| Run benchmarks | go test -bench=. -benchmem |
| Run 10s each | go test -bench=. -benchtime=10s |
| Run 10 iterations | go test -bench=. -count=10 |
| Compare | benchstat before.txt after.txt |
| CPU profile | go test -bench=. -cpuprofile=cpu.prof |
| Memory profile | go test -bench=. -memprofile=mem.prof |
| Interactive pprof | go tool pprof -http=:8080 cpu.prof |
Related Skills
- go: Idiomatic Go patterns for errors, interfaces, concurrency, and packages