liveBook · Manning

Benchmark

As explained in Go in Action, Second Edition

Benchmark testing measures how code performs under repeated execution with controlled inputs and conditions.

Benchmark testing measures performance by repeatedly executing a function under consistent conditions. It reveals average processing time and helps compare alternative implementations before performance problems become production concerns. section 8.7.1

A practical benchmark follows a small, repeatable workflow:

  • Start with a realistic implementation and establish a baseline. section 8.7.1
  • Write a benchmark function that accepts *testing.B rather than *testing.T. section 8.7.1
  • Run the operation through b.N iterations, checking that each result remains valid. section 8.7.1
  • Run go test -bench=. and compare iterations, nanoseconds per operation, and the environment reported with the result. section 8.7.1
  • Keep comparison parameters equivalent while changing the implementation under test. section 8.7.1

Comparing string-generation implementations

A RandomString function first builds a byte slice, then a second implementation uses strings.Builder. Separate benchmarks call each function with varying lengths and verify the returned length. Running go test -bench=. produces averaged nanoseconds-per-operation results, making the two approaches directly comparable; the measured result depends partly on the processor and operating system. section 8.7.1

Listing 8.34 xstrings_test.go: Simple string-generation method
import (
	"strings"
	"testing"

	xstring "github.com/go-in-action/chpt_8/benchmark/xstring"
)

func BenchmarkRandomString(b *testing.B) { #1
	for i := range b.N { #2
		res := xstring.RandomString(i) #3
		if len(res) != i {
			b.Error("result has the wrong length")
		}
	}
}

Inspect the benchmark structure: testing.B supplies the iteration count, the loop invokes the function repeatedly, and the assertion catches invalid results. section 8.7.1

How Go in Action, Second Edition covers it

How deep it goes
Explains testing.B, b.N, result validation, command execution, and output fields, but does not develop profiling internals.
Examples
Demonstrates naive byte-slice and strings.Builder random-string generators with paired benchmark functions and command output.
What you can do after
Apply it via Go's built-in testing library to establish baselines and compare function implementations using measured operation times.
How it connects
Connects benchmark testing with unit testing, fuzz testing, code coverage, test-driven development, and profiling.

Also explained in

Compare how 23 books explain benchmark →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.