โฑ๏ธBenchmarkingLESSON

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

FlagMeaning
-bench=.Run all benchmarks (regex match)
-benchmemReport memory allocations per op
-benchtime=5sRun for at least 5 seconds
-count=3Repeat 3 times for variance

Reading the output

  • ns/op โ€” nanoseconds per operation
  • B/op โ€” bytes allocated per operation
  • allocs/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?