Go · Stage 11 – Beyond the Basics · Lesson 62 of 64

Basic Benchmarking

Measure how quickly a small operation runs.

Go code

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(2, 3)
    }
}
Line-by-line explanation
  1. The name begins with Benchmark.
  2. B manages measurement.
  3. Go chooses b.N for reliable timing.
  4. The operation runs repeatedly.
Expected output
BenchmarkAdd-8    1000000000    0.3 ns/op

Numbers vary by computer and Go version.

Run benchmarks with go test -bench=.. Measure realistic work and compare several runs.