×

go · level 3 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A runs your code b.N times and reports the cost.

A benchmark measures how fast code runs. testing.Benchmark takes a function with a b *testing.B, and your function runs the code b.N times in a loop. Go picks b.N itself, raising it until the timing is steady, then reports the time per operation in ns/op.

Speed is not the only cost. Each , a request for fresh memory, makes more work for Go's memory clean-up. b.ReportAllocs() records allocations too, and testing.AllocsPerRun counts them for a single function.

On your own computer, benchmarks live in _test.go files and run with go test -bench=.. For a whole program, a from pprof shows where the time really goes. Measure first: guesses about the slow part are often wrong.

package main
import (
	"fmt"
	"strings"
	"testing"
)
func main() {
	words := strings.Fields("the quick brown fox jumps over the lazy dog")
	r := testing.Benchmark(func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			strings.Join(words, " ")
		}
	})
	fmt.Println("ran", r.N > 0)
	fmt.Println(r)
	fmt.Println("allocations per join:", r.AllocsPerOp())
}

Your numbers will differ from anyone else's, and from your own next run, so compare them and never copy them into a test.