Benchmarking Golang Code

Go provides a benchmarking tool as part of its standard testing package to measure the performance of your code. To use benchmarking in Go, you write a benchmark function and run it with the “go test” command using the -bench flag followed by a regular expression that matches the benchmark function names.

Here is an example:


package main

import "testing"

func BenchmarkAdd(b *testing.B) {
	x := 1
	y := 2
	for i := 0; i < b.N; i++ {
		add(x, y)

func add(x, y int) int {
	return x + y

To run the benchmark:

go test -bench=".*" -benchmem

The benchmark function must run the code being tested b.N times in a loop, where b.N is an input parameter provided by the benchmark framework. The benchmark tool will automatically determine the number of iterations that gives the benchmark function enough time to produce a meaningful result, and will report the average time per iteration.

Here’s an example of the output from a benchmark function in Go:

goos: linux
goarch: amd64
pkg: random-go
cpu: AMD Ryzen 7 PRO 5850U with Radeon Graphics     
BenchmarkAdd-16     1000000000      0.2270 ns/op        0 B/op        0 allocs/op
ok      random-go       0.253s

The output shows the following information:

goos: The operating system where the benchmark was executed, which in this case is Linux. goarch: The architecture for which the code was compiled, which in this case is AMD64. pkg: The name of the Go package that was benchmarked. cpu: Information about the CPU where the benchmark was run.

The benchmark results show the performance of a specific function named Add, which was executed 1 billion (1,000,000,000) times during the benchmark. The function was so fast that it took only 0.2272 nanoseconds on average to complete each operation. The benchmark indicates that the function did not perform any memory allocations (0 B/op) and there were no allocations (0 allocs/op).

Finally, the output indicates that the benchmark passed successfully and the total time taken by the benchmark was 0.253 seconds.