Linux Format

WRITING BENCHMARKS IN GO

-

There are some rules about benchmark writing in Go. First, the go test subcommand is responsibl­e for benchmarki­ng 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.

Additional­ly, 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.

Benchmarki­ng 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 expression­s. 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 benchmarki­ng is the interpreta­tion of the results – provided that your benchmarki­ng functions are working, of course.

Newspapers in English

Newspapers from Australia