WRITING BENCHMARKS IN GO
There are some rules about benchmark writing in Go. First, the go test subcommand is responsible for benchmarking a program. Then, it’s considered best practice for benchmark functions to be included in Go files that end with _test.go. All benchmark function names should begin with Benchmark – a function that begins with a lowercase B isn’t treated as a benchmark function by Go.
Additionally, benchmark functions must have a given signature, which means that benchmark functions should accept a *testing.B parameter only and return no values. Finally, the package that contains benchmark functions must include the “testing” standard Go package.
Benchmarking functions are executed with commands similar to the following:
$ go test -bench=. file.go file_test.go
The value of the -bench parameter specifies the benchmark functions that will be executed using regular expressions. The . value used is a regular expression that matches all valid defined benchmark functions. If you omit the -bench parameter or if there are no matches, then no benchmark function will be executed.
Each benchmark is executed for at least one second by default. If a benchmark function returns in a time that’s less than one second, the b.N value is increased and the function is run again. The first time the value of b.N is 1, then it becomes 2, 5, 10, 20, 50, and so on. This happens because the faster the function, the more times you need to run it to obtain more accurate results. However, the difficult thing in benchmarking is the interpretation of the results – provided that your benchmarking functions are working, of course.