Benchmarks
A benchmark is func BenchmarkXxx(b *testing.B) in a _test.go file. go test -bench runs the function in a loop b.N times and reports ns/op, and optionally allocs/op.
Detailed Explanation
You think append in a loop is hot. A benchmark measures it. The harness picks b.N so the run lasts long enough to be stable. You write for i := 0; i < b.N; i++ { work() }. Setup that should not be timed goes before the loop, or you call b.ResetTimer() after setup.
Reports. ns/op is nanoseconds per iteration. -benchmem adds allocs/op and B/op. Those allocation numbers are why benchmarks pair with escape analysis: a surprising allocs/op of 1 on a function you thought was stack-only is a heap escape.
Fairness. Do not let the compiler throw away work: assign to a package-level sink or use b.SetBytes and actually consume the result. Keep input sizes realistic. A benchmark of n=3 does not predict n=3e6.
b.Run and b.ReportMetric. Sub-benchmarks table-drive sizes. ReportMetric adds a custom column. b.RunParallel is for contended mutexes and atomics across goroutines.
What it costs. Benchmarks are not unit tests; they can be slow. Name them so -bench=Parse does not run the world, or use -bench=^BenchmarkParse$. Commit benchmark results only as comments or in a perf repo; they vary by machine.
Code Examples
package parse
import "testing"
func BenchmarkParsePort(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _ = parsePort("8080")
}
}
func parsePort(string) (int, error) { return 8080, nil }var sink int
func BenchmarkSum(b *testing.B) {
s := make([]int, 1024)
b.ResetTimer()
for i := 0; i < b.N; i++ {
sink = sum(s)
}
}
func sum(s []int) int {
n := 0
for _, v := range s {
n += v
}
return n
}go test -bench=ParsePort -benchmem ./...Common Gotchas
Dead-code elimination can make a benchmark report 0 ns
sink the result.
Including setup inside `b.N` measures the wrong thing
reset the timer or allocate outside.
Default `go test` does not run benchmarks
you need `-bench`.
Compare two implementations on the same machine, same `GOMAXPROCS`
Compare two implementations on the same machine, same `GOMAXPROCS`