Skip to content

Instantly share code, notes, and snippets.

@refs
Created March 22, 2018 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save refs/98d9ad16345372ace897f53e9f4cd8e9 to your computer and use it in GitHub Desktop.
Save refs/98d9ad16345372ace897f53e9f4cd8e9 to your computer and use it in GitHub Desktop.

Benchmarking in Go

Steps

go get golang.org/x/tools/cmd/benchcmp

write a benchmark for the function:

package main

import (
	"testing"
)

func BenchmarkMain(b *testing.B) {
	main()
}

run the benchmark as:

go test -count=1 -benchmem -run=^$ github.com/zyxan/some_go_project -bench ^BenchmarkMain$ | tee ~/Desktop/old.out

keep the old.txt file safe while you "improve" your implementation. Once you have something you want to compare, run the benchmark again only this time piping it into ~/Desktop/new.out

Compare results with benchcmp, seeing something like:

benchcmp old.txt new.txt

benchmark           old ns/op       new ns/op       delta
BenchmarkMain-8     16658672431     12593963945     -24.40%

benchmark           old allocs     new allocs     delta
BenchmarkMain-8     3679046        4220014        +14.70%

benchmark           old bytes     new bytes      delta
BenchmarkMain-8     157065264     3379300000     +2051.53%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment