Measure CPU time and allocations with benchmarks
Measure CPU time and allocations with benchmarks
A benchmark measures the cost of a repeatable operation under a particular workload. In Go 1.23, a BenchmarkX function receives *testing.B and performs the operation b.N times; the harness adjusts N. Use go test -run=^$ -bench=. -benchmem -count=5 after correctness tests. The reported ns/op is elapsed time per operation, not a direct measurement of CPU cycles; CPU profiles help explain where CPU time is spent.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "testing")
var sink string
func join(a, b string) string { return a + ":" + b }func TestLesson(t *testing.T) { if join("go", "test") != "go:test" { t.Fatal("join") }}func BenchmarkJoin(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { sink = join("go", "test") }}Run the benchmark command separately. The global sink makes the result observable; the fixed inputs may still enable compiler optimizations. B/op is allocated bytes per operation and allocs/op is allocation count per operation, not live heap size. The ordinary test checks behavior without imposing a timing threshold.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonExclude setup and report processed bytes
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "bytes" "testing")
var found int
func TestLesson(t *testing.T) { if bytes.Count([]byte("aba"), []byte("a")) != 2 { t.Fatal("count") }}func BenchmarkCount(b *testing.B) { data := bytes.Repeat([]byte("ab"), 2048) needle := []byte("a") b.SetBytes(int64(len(data))) b.ResetTimer() for i := 0; i < b.N; i++ { found = bytes.Count(data, needle) }}Allocating the input before ResetTimer excludes its setup from the timed and allocation interval. SetBytes describes bytes processed per iteration and enables MB/s reporting. Keep input shape, toolchain, machine, CPU setting and benchmark command constant; save multiple runs rather than comparing one noisy number. Do not compare race-instrumented timing with normal timing.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Benchmark strings.Count on a 1024-byte alternating input; verify the count is 512, exclude setup and report bytes. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Performance engineering 01: Measure CPU time and allocations with benchmarks
Check the lesson objective before moving on.
What does B/op measure?
Why call ResetTimer after input preparation?