@faizmokh's blog

How to use Go examples and benchmarks

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

Examples

Structure

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

Rules

How to Use

Sample Execution

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

Extras


Benchmarks

Structure

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

Rules

How to Use

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

#go #til