Go Benchmarks

Sep 24, 2015

Benchmarks

Benchmarks are tests for performance. It’s pretty useful to have them in
project and compare results from commit to commit. Go has very good tooling for
writing and executing benchmarks. In this article I’ll show how to use package
testing for writing benchmarks.

We see here that one iteration takes 206 nanoseconds. That was easy, indeed.
There are couple of things more about benchmarks in Go, though.

What you can benchmark?

By default go test -bench=. tests only speed of your code, however you can
add flag -benchmem, which will also test a memory consumption and an
allocations count. It’ll look like:

PASS
BenchmarkSample 10000000 208 ns/op 32 B/op 2 allocs/op

Here we have bytes per operation and allocations per operation. Pretty useful
information as for me. You can also enable those reports per-benchmark with
b.ReportAllocs() method.
But that’s not all, you can also specify a throughput of one operation with
b.SetBytes(n int64) method. For example:

Writing profiles

You can read how to analyze profiles in awesome blog post on blog.golang.org
here.

Conclusion

Benchmarks is awesome instrument for programmer. And in Go you to writing and
analyzing becnhmarks is extremely easy. New benchmarks allows you to find
performance bottlenecks, weird code (efficient code is often simpler and more
readable) or usage of wrong instruments. Old benchmarks allow you to be more
confident in your changes and could be another +1 in review process. So,
writing writing benchmarks has enormous benefits for programmer and code and
I encourage you to write more. It’s fun!