0
0
GoHow-ToBeginner · 4 min read

How to Write Benchmark Tests in Go: Simple Guide

In Go, write benchmark tests by creating functions starting with Benchmark and accepting *testing.B as a parameter. Use b.N in a loop to run the code multiple times, then run benchmarks with go test -bench=..
📐

Syntax

A benchmark function in Go must start with Benchmark and take a single parameter b *testing.B. Inside, use a loop from 0 to b.N to run the code you want to measure repeatedly. The b.N value is automatically adjusted by Go to get reliable timing.

go
func BenchmarkFunctionName(b *testing.B) {
    for i := 0; i < b.N; i++ {
        // code to benchmark
    }
}
💻

Example

This example benchmarks a simple function that concatenates two strings. It shows how to write the benchmark function and run it using go test -bench=..

go
package main

import (
    "testing"
)

func concatStrings(a, b string) string {
    return a + b
}

func BenchmarkConcatStrings(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = concatStrings("hello", "world")
    }
}
Output
goos: linux goarch: amd64 pkg: example BenchmarkConcatStrings-8 1000000000 0.292 ns/op PASS ok example 0.345s
⚠️

Common Pitfalls

Common mistakes include not using b.N in the loop, which causes the benchmark to run only once and gives unreliable results. Another mistake is including setup code inside the loop, which skews the timing. Setup should be done before the loop.

go
func BenchmarkWrong(b *testing.B) {
    // Setup inside loop (wrong)
    for i := 0; i < b.N; i++ {
        data := make([]int, 1000) // setup inside loop
        _ = len(data)
    }
}

func BenchmarkRight(b *testing.B) {
    data := make([]int, 1000) // setup outside loop
    for i := 0; i < b.N; i++ {
        _ = len(data)
    }
}
📊

Quick Reference

  • Benchmark function name must start with Benchmark.
  • Parameter must be b *testing.B.
  • Use for i := 0; i < b.N; i++ to run code repeatedly.
  • Run benchmarks with go test -bench=..
  • Keep setup code outside the loop.

Key Takeaways

Benchmark functions must start with Benchmark and accept *testing.B.
Use b.N in a loop to run the code multiple times for accurate timing.
Run benchmarks using go test -bench=.
Keep setup code outside the benchmark loop to avoid skewed results.
Benchmark tests help measure performance easily in Go.