...

/

Benchmarking and Fuzzing

Benchmarking and Fuzzing

Learn about benchmarking and fuzzing, two important features provided by Go’s testing package .

Benchmarking

At times, we need to make sure that a test executes within an acceptable amount of time. To check this, we can take advantage of the benchmarks that are already provided by the testing package of the Go standard library. Let’s learn how to write a benchmark in Go:

package benchmarking

import "testing"

func BenchmarkFizzBuzz(b *testing.B) {
	for i := 0; i < b.N; i++ {
		FizzBuzz(10)
	}
}
Benchmarking the FizzBuzz function

In the example above, we wrote a benchmark function on the FizzBuzz function. As we can see, there are a lot of similarities with writing unit tests:

  • The name of a benchmark function must be BenchmarkXxx, where Xxx is the name of the production function to which the benchmark is referred.
  • A benchmark function accepts, as a parameter, b of type *testing.B.
  • In the for loop, we iterate up to b.N, where N is a randomly generated number indicating how many times we have to run the FizzBuzz function.

To run this benchmark, we use the go test -bench=. command, where . is a regular expression that selects which benchmarks to run. With ., we’re saying to run every defined benchmark.

Reading the results

After we get the results in the console, we need to know how to read them. Let’s look at an example of what we can get by running the previous benchmark:

goos: linux
goarch: amd64
pkg: benchmarking
cpu: Intel(R) Xeon(R) CPU @
...