How to use Go examples and benchmarks

I learned about Go examples and benchmarks today. They are parts of Go default package testing.

Examples

  • Go Examples are executed just like tests
  • They are compiled and optionally executed as part of unit tests
  • It resides in the package *_test.go files

Structure

1func ExampleRepeat() {
2  repeated := Repeated("x", 5)
3  fmt.Println(repeated)
4  // output: xxxxx
5}

Rules

  • Function name must be prefix with Example
  • It must have // output: result

How to Use

  • to run the test with example, use: go test -v

Sample Execution

1$ go test -v
2=== RUN   TestRepeat
3--- PASS: TestRepeat (0.00s)
4=== RUN   ExampleRepeat
5--- PASS: ExampleRepeat (0.00s)

Extras

  • It will not run if you remove the // output comment.
  • These examples can be display in godoc as part of the documentations
  • To see the examples, run go doc -http:6060 and navigate to http://localhost:6060/pkg/ and you will find the examples in the package documentation.

Benchmarks

  • Just like Examples above, Benchmarks are executed by go test

Structure

1func BenchmarkRepeat(b *testing.B) {
2	for i := 0; i < b.N; i++ {
3		Repeat("a", 100)
4	}
5}

Rules

  • Function name must be prefix with Benchmark
  • testing.B give you access to b.N.
  • During benchmarking process, it will run b.N times and measure the duration it takes

How to Use

  • To run the test with benchmarks, use: go test -bench=.

Sample Execution

1$ go test -bench=.
2goos: darwin
3goarch: amd64
4pkg: github.com/faizmokhtar/go-with-test/3-repeat
5BenchmarkRepeat-8         300000              5485 ns/op
6PASS
7ok      github.com/faizmokhtar/go-with-test/3-repeat    1.714s

References:

  1. https://golang.org/pkg/testing/#hdr-Benchmarks
  2. https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go