Benchmarking code in Go

To create a unit test in Go<, we simple create a function with Test as the first part of the name, see my previous post on Unit testing in Go.

We can also write performance/benchmarking test code by creating a function with Benchmark as the first part of the function name, i.e. BenchmarkDataRead and it takes on the same format as a unit test, for example

func BenchmarkEcho(b *testing.B) {
	expected := "Hello"
	actual := test.Echo("Hello")

	if actual == expected {
		b.Error("Test failed")
	}
}

Our benchmark is passed a testing.B type which gives us functionality as per testing.T, in that we can fail a benchmark test etc. Obviously, for a benchmarking type, we also have the ability to start and stop the timer, for example if we have initialization and cleanup code we might want to exclude these from the benchmark by just wrapping the key code in a b.StartTimer and b.StopTimer section, i.e.

func BenchmarkEcho(b *testing.B) {
	expected := "Hello"

	b.StartTimer()
	actual := test.Echo("Hello")
	b.StopTimer()

	if actual != expected {
		b.Error("Test failed")
	}
}