Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Logging, Flags and Testing

Go testing.B benchmarks

Reference for Go testing.B: BenchmarkXxx functions, b.Loop and b.N, ResetTimer, ReportAllocs, sub-benchmarks, RunParallel, go test -bench and reading ns/op results.

A benchmark is a function named BenchmarkXxx that takes a *testing.B. The framework calls it repeatedly with growing iteration counts until the timing is stable, then reports the average time per operation. You write the loop; go test -bench does the statistics.

Since Go 1.24 the recommended loop is for b.Loop() { ... }. The older form, for i := 0; i < b.N; i++ { ... }, still works and is common in existing code.

Go
func BenchmarkJoin(b *testing.B) {
	parts := []string{"a", "b", "c"}
	for b.Loop() {
		strings.Join(parts, ",")
	}
}
// go test -bench=. -benchmem

Try it

Timings differ on every machine, so these examples print results that are stable: allocation counts and how many times the framework calls your function. Sub-benchmarks with b.Run are shown in the notes below. testing.Benchmark runs a benchmark function from ordinary code.

Go Allocations: concatenation versus Builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go b.Loop versus b.N, and ResetTimer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func BenchmarkXxx(b *testing.B)

func (b *B) Loop() bool                        // Go 1.24
func (b *B) ResetTimer()
func (b *B) StopTimer()
func (b *B) StartTimer()
func (b *B) ReportAllocs()
func (b *B) SetBytes(n int64)
func (b *B) ReportMetric(n float64, unit string)
func (b *B) Run(name string, f func(b *B)) bool
func (b *B) RunParallel(body func(*PB))
func Benchmark(f func(b *B)) BenchmarkResult
Name Description
b.N Number of iterations the framework wants this time. Use it only with the classic loop.
b.Loop() Returns true while more iterations are needed. Setup before the loop and cleanup after it run once per call, and the compiler cannot optimize the loop body away.
ResetTimer Zeroes elapsed time and allocation counters. Call it after setup.
SetBytes(n) Declares bytes processed per iteration so the output includes MB/s.
ReportMetric Adds a custom column, such as items/op.
RunParallel Runs body on GOMAXPROCS goroutines; each calls pb.Next() in a loop. For contention tests.

Result fields: BenchmarkResult has N, T, Bytes, MemAllocs, MemBytes and methods NsPerOp(), AllocsPerOp(), AllocedBytesPerOp().

Usage notes

  • Sub-benchmarks. b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) { ... }) reports one line per size, named BenchmarkSort/n=100; select with -bench=Sort/n=100.
  • Run them with go test -bench=. -benchmem -run=^$. The -run=^$ skips normal tests. Use -benchtime=2s or -benchtime=500x for a fixed time or count, -count=10 for repeats, and -cpu=1,4 to vary GOMAXPROCS.
  • Output format. A line like BenchmarkJoin-8 20000000 62.3 ns/op 16 B/op 1 allocs/op means 8 CPUs, the iteration count, time, bytes and allocations per operation.
  • Beware dead-code elimination. With the classic loop, assign results to a package-level variable (a "sink") so the compiler cannot remove the call. b.Loop handles this for the call expression in the loop body.
  • Compare with benchstat. One run is noise. Run each side several times with -count, then compare with the benchstat tool.
  • Setup inside the loop is measured. Use ResetTimer, or StopTimer and StartTimer around per-iteration setup (those calls are slow themselves, so avoid them in tight loops).
  • Avoid I/O and the network in micro-benchmarks; they measure the environment, not your code.
  • Profile from the benchmark with -cpuprofile and -memprofile, then open the file with go tool pprof.
  • Cache effects and input size matter. Benchmark realistic sizes, not just tiny inputs.