Benchmarking
Why benchmark?
Profile before optimising. Without measurements you are guessing. Go's testing package includes a built-in benchmarking framework that runs functions under controlled conditions and reports time-per-operation and allocations.
Writing a benchmark
Benchmark functions live in _test.go files and follow the BenchmarkXxx(b *testing.B) signature:
The b.N loop is run enough times for the framework to get a stable measurement.
Running benchmarks
| Flag | Meaning |
|---|---|
-bench=. | Run all benchmarks (regex match) |
-benchmem | Report memory allocations per op |
-benchtime=5s | Run for at least 5 seconds |
-count=3 | Repeat 3 times for variance |
Reading the output
ns/opโ nanoseconds per operationB/opโ bytes allocated per operationallocs/opโ heap allocations per operation
b.ResetTimer โ exclude setup time
Call b.ResetTimer() after any setup that should not be counted in the benchmark time.
b.RunParallel โ concurrent benchmarks
b.RunParallel runs the closure in GOMAXPROCS goroutines simultaneously โ useful for benchmarking concurrent data structures or measuring lock contention.
Comparing benchmarks with benchstat
After collecting results with -count=5, use benchstat to get statistically significant comparisons:
Knowledge Check
What does b.N represent in a benchmark loop?
When should you call b.ResetTimer()?
What does the `-benchmem` flag add to benchmark output?