In this tutorial, we'll learn how to write benchmark tests in Go. Benchmarking is a critical part of performance optimization as it allows us to measure the speed of different parts of our code and identify areas that may require optimization.
Benchmark tests in Go are written in a similar manner to regular tests, but they are run differently. The testing
package in Go provides a B
type that we use to write benchmarks.
To write a benchmark test, we define a function with the following signature:
func BenchmarkName(b *testing.B) {
// benchmark code here
}
You can replace Name
with the name of your benchmark.
To run a benchmark test, use the following command:
go test -bench=.
This command runs all benchmarks in your current directory.
Let's create a benchmark test for a function that adds two integers.
func add(x, y int) int {
return x + y
}
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add(4, 2)
}
}
In this code:
add
is a simple function that adds two integers.BenchmarkAdd
is our benchmark test. It runs the add
function b.N
times.The b.N
value is managed by the testing
package. It starts with a small number and increases as the benchmarking continues until it reaches a steady state.
Expected output:
goos: linux
goarch: amd64
pkg: github.com/username/repo
BenchmarkAdd-8 1000000000 0.275 ns/op
PASS
ok github.com/username/repo 0.556s
This output shows:
- the number of times the operation was run (1000000000
)
- the average time per operation (0.275 ns/op
)
In this tutorial, you learned what benchmarking is, why it's important, and how to write and run benchmark tests in Go. The next step is to start writing benchmarks for your code and identify areas for optimization.
Additional resources:
- Go testing
package documentation
- Writing benchmarks in Go - blog post
Write a benchmark test for a function that finds the largest number in a list.
Write a benchmark test for a function that sorts a list of numbers.
Write a benchmark test for a function that reverses a string.
Solutions with explanations and tips for further practice can be found in this repository.