Go Examples and Benchmarks

Friday, 3 August 2018

Tags: go til

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

Examples

Structure

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

Rules

How to Use

Sample Execution

$ go test -v
=== RUN   TestRepeat
--- PASS: TestRepeat (0.00s)
=== RUN   ExampleRepeat
--- PASS: ExampleRepeat (0.00s)

Extras


Benchmarks

Structure

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

Rules

How to Use

Sample Execution

$ go test -bench=.
goos: darwin
goarch: amd64
pkg: github.com/faizmokhtar/go-with-test/3-repeat
BenchmarkRepeat-8         300000              5485 ns/op
PASS
ok      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