Micro-benchmarking

Micro-benchmarking in Go: A running coach never times one lap. Press the button once and you have measured the runner's start, the coach's thumb, a gust down…

The Analogy: The Coach With a Stopwatch

A running coach never times one lap. Press the button once and you have measured the runner's start, the coach's thumb, a gust down the back straight and the moped that went past the fence -- all mixed into a single number with no way to separate them. So the coach times forty laps and divides. The number that comes out is not the truth about any particular lap; it is the truth about the runner, which is the thing the coach actually wanted.

The coach also decides how many laps, and decides it from the event. A sprinter gets thirty reps because each one lasts ten seconds and the stopwatch is only accurate to a tenth. A marathon runner gets one, because a second of timing error against two hours does not matter. You do not tell Go's benchmark framework how many iterations to run either. It runs the body once, looks at how long that took, and keeps growing the count until the total is long enough that the clock's own error has been diluted away.

Then there is the track. A time set on grass, uphill, in a headwind, is not comparable to a time set on a rubber track in still air, and the coach who forgets this will "improve" a runner by moving to a better venue. Every benchmark number you will ever see is a number for one machine, one CPU, one thermal state, one Go version. Comparing today's run on a laptop that has been busy for six hours against last week's run on a cold one is measuring the laptop, and the fix is the same one the coach uses: repeat the measurement, on the same track, and treat a small difference as noise until it survives repetition.

And when the stopwatch says four seconds, it does not say why. It cannot tell you that the runner was slow out of the blocks, or faded in the last twenty metres, or is carrying an injury. That needs a different instrument -- somebody watching the whole race and noting where the time went. In Go that instrument is the profiler, and it is the subject of the next lesson. The stopwatch tells you whether a change helped. The profiler tells you what to change.


Syntax or Core Structure

A benchmark is a function in a _test.go file whose name starts with Benchmark and which takes a *testing.B. The framework calls it, sets b.N, and the function's job is to do the work b.N times. Here are two implementations of the same job and one benchmark for each.

// strutil.go
package strutil

import "strings"

// JoinPlus builds the result one += at a time, allocating a new string
// on almost every step.
func JoinPlus(parts []string, sep string) string {
	out := ""
	for i, p := range parts {
		if i > 0 {
			out += sep
		}
		out += p
	}
	return out
}

// JoinBuilder does the same job with one buffer that grows a few times.
func JoinBuilder(parts []string, sep string) string {
	var b strings.Builder
	for i, p := range parts {
		if i > 0 {
			b.WriteString(sep)
		}
		b.WriteString(p)
	}
	return b.String()
}
// strutil_test.go
package strutil

import "testing"

var parts = []string{"alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"}

// sink is a package level variable. Assigning to it stops the compiler
// deciding the call has no effect and deleting it.
var sink string

func BenchmarkJoinPlus(b *testing.B) {
	for i := 0; i < b.N; i++ {
		sink = JoinPlus(parts, ",")
	}
}

func BenchmarkJoinBuilder(b *testing.B) {
	for i := 0; i < b.N; i++ {
		sink = JoinBuilder(parts, ",")
	}
}

Run them with go test -run=^$ -bench=. -benchmem ./.... The -run=^$ matches no test names, so only the benchmarks execute; -bench takes a regular expression, and . matches everything. -benchmem adds the two allocation columns, which are the columns that will still be true on somebody else's machine.

Output:

The absolute times below came from one particular laptop and yours will differ by a factor of two in either direction. The ratio between the two lines, and both allocation columns, are the parts that transfer.

goos: linux
goarch: amd64
pkg: example.com/strutil
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkJoinPlus-8         4692518        248.6 ns/op       472 B/op       14 allocs/op
BenchmarkJoinBuilder-8     10395624        115.2 ns/op       120 B/op        4 allocs/op
PASS
ok      example.com/strutil     2.612s

Read the columns left to right. -8 is GOMAXPROCS, not a version. 4692518 is the b.N the framework settled on -- multiply it by ns/op and you get about 1.2 seconds, because the default -benchtime is 1s and the ramp overshoots slightly. ns/op is the total time divided by that count. B/op and allocs/op are bytes and allocation calls per iteration, and they explain the time: fourteen allocations became four, and the run got twice as fast.


Technical Depth: The Framework, the Optimiser and the Noise

The loop, old and new

Go 1.24 added b.Loop, and it is now the form to write:

func BenchmarkJoinBuilder(b *testing.B) {
	parts := loadParts()          // not timed
	for b.Loop() {
		JoinBuilder(parts, ",")   // not deleted, even with the result discarded
	}
}

It does three things the b.N loop does not. The timer starts on the first call and stops when it returns false, so setup above the loop and cleanup below it are excluded without a ResetTimer. The body runs exactly once per -count from the framework's point of view, so expensive setup is not repeated for each ramp step. And the compiler is prevented from optimising away calls whose results are unused, which makes the sink variable unnecessary. The for i := 0; i < b.N; i++ form still compiles, still works, and is what you will find in every codebase written before 2026, so you need to be able to read both.

The testing.B surface

MemberPurpose
b.NIteration count chosen by the framework. Never assign to it, never use it as data.
b.Loop() boolGo 1.24 loop condition. Handles the timer and defeats dead code elimination.
b.ResetTimer()Discard everything timed so far. Use after setup in a b.N loop.
b.StopTimer() / b.StartTimer()Bracket work that should not count. Each call costs tens of nanoseconds.
b.ReportAllocs()Turn on the allocation columns for this benchmark without -benchmem.
b.SetBytes(n)Declare bytes processed per iteration; adds an MB/s column.
b.ReportMetric(v, unit)Add your own column, for example cache-misses/op or docs/s.
b.Run(name, fn)A sub-benchmark, for table driven size sweeps.
b.RunParallel(fn)Run the body on GOMAXPROCS goroutines to measure contention.
b.Cleanup(fn)Register teardown, run after the benchmark finishes.
b.Fatal / b.ErrorA benchmark is still a test. Fail loudly rather than measuring nonsense.

The flags that matter

FlagEffect
-bench=<regexp>Run matching benchmarks. Required -- without it, none run. -bench=. runs all.
-run=^$Match no tests, so the run is benchmarks only.
-benchmemAdd B/op and allocs/op to every line.
-benchtime=3sTarget duration per benchmark. -benchtime=100x fixes the count instead.
-count=10Repeat the whole set ten times. This is what makes statistics possible.
-cpu=1,2,4,8Re-run at each GOMAXPROCS. Only interesting with RunParallel or shared state.
-cpuprofile / -memprofileWrite a profile while benchmarking. The bridge to the next lesson.
-memprofilerate=1Sample every allocation rather than one in 512 KB, for hunting a stray one.
-timeout=0Disable the ten minute default when -count and -benchtime are both large.

The optimiser is an adversary

The Go compiler is entitled to delete work whose result nobody uses. A benchmark whose body computes a value and throws it away can be optimised into an empty loop, and an empty loop of a hundred million iterations reports something like 0.2543 ns/op -- a number smaller than a single memory access, which is the tell. Three defences, in order of preference: use b.Loop, which the compiler is required to treat as observable; assign the result to a package level sink; or pass the result to b.ReportMetric or a b.Fatal guard that can never fire. Never "fix" it by adding fmt.Sprint to the loop, because then you are benchmarking fmt.

Inlining is the other half of this. A one line function called in a tight loop may be inlined into the benchmark and then partially folded into constants, so you measure a version of your function that does not exist anywhere else in the program. go build -gcflags=-m prints inlining decisions, and //go:noinline on the function under test will suppress it -- but if production inlines it, suppressing it in the benchmark makes the benchmark the lie.

b.N is not yours, and the body must be repeatable

The framework calls your function once with b.N == 1, measures, then ramps -- roughly by the ratio needed to reach -benchtime, capped so it grows at most a hundredfold per step -- and calls it again from scratch. Two consequences. First, make([]byte, b.N) is a bug: it allocates a slice that grows with the iteration count, so the benchmark measures allocation size, not your code. Second, the loop body must do the same amount of work every time. A body that sorts its input measures a random permutation on the first iteration and an already sorted slice on every one after it; a body that appends to a package level slice measures a slice that gets longer. If the work is destructive, copy the input inside the loop and pay for the copy in both variants, or use b.StopTimer around the reset and accept the overhead.

One number is not a measurement

A single benchmark line is one sample from a noisy process. Frequency scaling, thermal throttling, another process on the same core, the position of your data in the cache, and the address randomisation the allocator gives you all move the result by a few percent, and a few percent is exactly the size of the improvement most people are trying to claim. The discipline is:

  • Run with -count=10 so you have a distribution rather than a point.
  • Save the output of the old code and the new code to separate files.
  • Compare them with benchstat (go install golang.org/x/perf/cmd/benchstat@latest), which prints a median with a percentage range and a note when the difference is not statistically significant.
  • Change one thing at a time, and quiesce the machine: plugged in, browser closed, no build running in another terminal.

benchstat will tell you ~ instead of a percentage when the two sets overlap too much to distinguish, and that verdict is the point of the exercise. A 3% win that benchstat refuses to confirm is not a win; it is a reason to make the change for clarity or not at all.

Sub-benchmarks and the shape of the curve

b.Run nests benchmarks the way t.Run nests tests, and the result is a size sweep in one function. This matters more than it sounds: a function's ranking against its alternatives is not a fact about the function, it is a fact about the function at a given input size. An algorithm with a fixed setup cost and linear growth loses to one with no setup and n log n growth until n gets large enough, and the size at which they cross is a property of your machine's cache and your data. Benchmark at the size your production inputs actually are, and if you do not know that size, that is the first thing to go and measure.

-bench matches sub-benchmark names too, using / as a separator, so -bench=Dedup/map runs one branch of the sweep and -bench=Dedup/.*n=512 runs one size across all variants.

RunParallel

b.RunParallel starts GOMAXPROCS goroutines, each pulling iterations from a shared counter:

func BenchmarkCounter(b *testing.B) {
	var c Counter
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			c.Inc()
		}
	})
}

The reported ns/op is still wall time per iteration, so a perfectly parallel operation gets faster as -cpu rises and a lock-bound one gets slower. That divergence is the whole reason to use it: it is how you show that a sync.Mutex counter degrades under contention while an atomic.Int64 does not. For single threaded code it adds only the counter's overhead and tells you nothing, so do not reach for it by default.


Real World Example: Where the Winner Changes With n

The requirement is "give me the distinct SKUs in this batch; order does not matter". Two obvious implementations satisfy it: walk the slice with a set, or copy, sort and compact. They are genuinely interchangeable under that requirement -- and only under it. If order mattered, the sorting version would not be a candidate no matter how fast it ran, which is the first question to ask before any benchmark: are these two functions doing the same job?

// dedup.go
package dedup

import "slices"

// Map returns the distinct strings in the order they first appeared.
func Map(in []string) []string {
	seen := make(map[string]struct{}, len(in))
	out := make([]string, 0, len(in))
	for _, s := range in {
		if _, dup := seen[s]; dup {
			continue
		}
		seen[s] = struct{}{}
		out = append(out, s)
	}
	return out
}

// Sort returns the distinct strings in sorted order. It copies first, so the
// caller's slice is untouched -- which is also what keeps a benchmark body
// that calls it repeatable.
func Sort(in []string) []string {
	out := make([]string, len(in))
	copy(out, in)
	slices.Sort(out)
	return slices.Compact(out)
}
// dedup_test.go
package dedup

import (
	"fmt"
	"slices"
	"strconv"
	"testing"
)

// input builds n SKUs of which roughly half are duplicates.
func input(n int) []string {
	in := make([]string, n)
	for i := range in {
		in[i] = "sku-" + strconv.Itoa(i%(n/2+1))
	}
	return in
}

// The benchmark is worthless without this. A fast wrong answer is not an
// optimisation, so the two implementations are proved equivalent first.
func TestBothAgree(t *testing.T) {
	for _, n := range []int{1, 8, 64, 512} {
		in := input(n)
		got := Map(in)
		slices.Sort(got)
		if want := Sort(in); !slices.Equal(got, want) {
			t.Fatalf("n=%d: got %v, want %v", n, got, want)
		}
	}
}

var sizes = []int{8, 64, 512, 4096}

func BenchmarkDedup(b *testing.B) {
	for _, n := range sizes {
		in := input(n)   // built once per size, above the timed loop
		b.Run(fmt.Sprintf("map/n=%d", n), func(b *testing.B) {
			b.ReportAllocs()
			for b.Loop() {
				Map(in)
			}
		})
		b.Run(fmt.Sprintf("sort/n=%d", n), func(b *testing.B) {
			b.ReportAllocs()
			for b.Loop() {
				Sort(in)
			}
		})
	}
}

Run it with go test -run=^$ -bench=Dedup -count=10 ./... in real life. A single run looks like this.

Output:

goos: linux
goarch: amd64
pkg: example.com/dedup
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkDedup/map/n=8-8        4712106     252.4 ns/op       320 B/op      3 allocs/op
BenchmarkDedup/sort/n=8-8       6408315     186.9 ns/op       128 B/op      1 allocs/op
BenchmarkDedup/map/n=64-8        793411      1489 ns/op      3392 B/op      3 allocs/op
BenchmarkDedup/sort/n=64-8       553262      2154 ns/op      1024 B/op      1 allocs/op
BenchmarkDedup/map/n=512-8        98042     12058 ns/op     26688 B/op      3 allocs/op
BenchmarkDedup/sort/n=512-8       41397     28914 ns/op      8192 B/op      1 allocs/op
BenchmarkDedup/map/n=4096-8       10000    102481 ns/op    213056 B/op      3 allocs/op
BenchmarkDedup/sort/n=4096-8       3820    313574 ns/op     65536 B/op      1 allocs/op
PASS
ok      example.com/dedup       9.784s

The sorting version wins at eight elements and loses everywhere after that, so the crossover on this machine sits somewhere between 8 and 64. That number is not a fact about Go; it is a fact about one CPU's cache, one allocator, and strings that happen to be five characters long and share a prefix. On a machine with slower memory the map's three allocations cost more and the crossover moves right; with longer strings each comparison costs more and it moves left. Anyone who tells you "always use a map for deduplication" has skipped the measurement, and so has anyone who tells you the opposite.

Check the growth rates, because they are the part that generalises. From 64 to 4096 the input grows 64-fold; Map goes from 1489 to 102481 ns, a factor of 69, which is linear plus a little cache tax. Sort goes from 2154 to 313574, a factor of 146, and n log n predicts 64 x (12/6) = 128. The shapes match the algorithms, which is the strongest evidence you have that the benchmark is measuring what you think it is. When the measured shape contradicts the algorithm, suspect the benchmark before the theory.

The allocation columns are the ones to trust across machines, because they are properties of the code rather than of the hardware. Sort makes exactly one allocation at every size -- the copy -- while Map makes three regardless of n, because both the map and the output slice are pre-sized from len(in) and never grow. Drop the size hints and Map would allocate a dozen times at n=4096 as the map rehashes and the slice doubles; allocs/op would jump while ns/op moved by less, and that gap is exactly what a reviewer wants to see before approving a change.

Two things this benchmark deliberately does not do. It never mutates in, so iteration nine thousand solves the same problem as iteration one -- had Sort called slices.Sort(in) directly, every iteration after the first would be sorting an already sorted slice and the number would be a fiction. And it builds the input above the timed loop, once per size, so strconv.Itoa is not in the measurement. With b.Loop that placement is enough; in the older b.N form you would need a b.ResetTimer() after it.


Common Mistakes

  1. Discarding the result in a b.N loop. The compiler deletes the call, the loop empties, and the report says 0.2543 ns/op -- less than one memory access, which is the giveaway. Use for b.Loop(), or assign to a package level sink. Any per-iteration number below about a nanosecond deserves suspicion before celebration.
  1. Timing the setup. Building the input, opening a file or decoding a fixture inside the loop measures that work as if it were yours. Hoist it above the loop; with the old b.N form, follow it with b.ResetTimer().
  1. A loop body that changes its own input. Sorting, appending to a shared slice, draining a channel or consuming a reader means iteration two solves a different problem from iteration one. The result is an average over a sequence of problems, none of which is the one you care about.
  1. Using b.N as data. make([]byte, b.N) or for i := 0; i < b.N; i++ { list = append(list, i) } makes the workload grow with the iteration count. The framework will report something, and it will be meaningless.
  1. Believing a single run. -count=1 gives you one sample from a process with several percent of noise. Two runs of identical code will differ; if you have not seen that for yourself, run the same benchmark twice before you trust any comparison.
  1. Comparing numbers from different machines, or different Go versions, in one table. A benchmark result is only comparable to another result from the same binary environment. Record goos, goarch, cpu and the Go version alongside anything you plan to quote.
  1. Benchmarking at a size you never use. Tuning the n=10 case for a service whose median batch is 50000 optimises the wrong end of the curve, and can reverse the ranking entirely -- as it does above.
  1. StopTimer and StartTimer inside a tight loop. Each pair costs tens of nanoseconds and forces the framework to re-read the clock, so bracketing a 20 ns operation measures mostly the brackets. Restructure so the untimed work happens once.
  1. Forgetting -benchmem. Without it you can halve ns/op while tripling allocations, ship it, and discover the cost later as GC pressure in a completely different part of the program. The allocation columns are cheap; always ask for them.
  1. Optimising without a correctness test. A benchmark proves a function is fast, never that it is right. Every performance change needs a test that fails if the behaviour changed, written before the optimisation and left in place afterwards.
  1. Micro-benchmarking before profiling. Making a function that accounts for 2% of runtime four times faster buys 1.5%. The stopwatch answers "did this change help"; only a profile answers "what should I change", and doing them in the wrong order is how afternoons disappear.

Best Practices

  • Write for b.Loop() on Go 1.24 and later. It handles the timer, keeps setup out of the measurement, and removes the need for a sink. Keep the b.N form only in code that must build against older toolchains, and there keep the sink with it.
  • Always -benchmem, and read allocs/op first. It is the number that survives a change of machine, it usually explains the timing, and reducing it is the single most reliable way to make Go code faster.
  • Never report a benchmark without -count and benchstat. Ten runs of old, ten of new, into two files, then benchstat old.txt new.txt. If it prints ~, you have no result yet -- get more samples or accept that the change is neutral.
  • Sweep the size with b.Run. One benchmark at one size is an anecdote; four sizes show you a curve, and the curve tells you whether the ranking you just measured holds at production scale.
  • Pair every benchmark with a test. Prove the alternatives agree, ideally over the same input sizes, before comparing their speed. Keep that test forever: it is what stops the next optimisation from being a regression.
  • Commit benchmarks alongside the code they measure. They document which operations were considered hot, they let the next person reproduce your claim, and run in CI with -benchtime=10x they at least prove they still compile and still agree.
  • Profile first, micro-benchmark second, and re-measure the whole program third. The profiler picks the target, the benchmark validates the fix, and an end-to-end measurement confirms that the win survived contact with everything else.
  • Quiesce the machine and say so. Plugged in, no browser, no other build, and the goos/goarch/cpu/version header pasted with the numbers. A benchmark without its environment is a number without units.

Practice Exercises

  1. Watch the Optimiser Delete Your Work: Write two benchmarks for JoinBuilder -- one b.N loop that discards the result, one that assigns to a package level sink -- and run both. Record the two ns/op values and explain the ratio. Then rewrite the discarding version with for b.Loop() and confirm the number returns to something believable.
  1. Move the Setup: Take BenchmarkDedup and deliberately move input(n) inside the timed loop, in both the b.Loop and the b.N form. Report how much each one inflates, then fix the b.N version with b.ResetTimer() and confirm it matches the b.Loop number.
  1. Find Your Own Crossover: Run the dedup sweep at n of 4, 8, 16, 32 and 64 with -count=10, and use benchstat to compare the two variants at each size. Report the size at which the winner changes on your machine, and whether benchstat is willing to call the difference significant at the size either side of it.
  1. Contention Has a Shape: Implement a counter twice, once with a sync.Mutex and once with an atomic.Int64, and benchmark both through b.RunParallel at -cpu=1,2,4,8. Plot or tabulate ns/op against GOMAXPROCS for each, and write two sentences explaining why one line rises and the other stays flat.