NOTE

4.3 benchmark

How to write and run Go benchmarks, inspect memory allocations, and generate CPU, memory, block, trace, and mutex profiles.

GoCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Usage

  • bench.go

    func Fib(n int) int {
    	if n < 2 {
    		return n
    	}
    	return Fib(n-1) + Fib(n-2)
    }
  • bench_test.go

    import (
    	"testing"
    )
    
    func BenchmarkFib(b *testing.B) {
    	// run the Fib function b.N times
    	for n := 0; n < b.N; n++ {
    		Fib(10)
    	}
    }
  • Tests:

    • go test -bench=.
      $ go test -bench=.
      goos: windows
      goarch: amd64
      pkg: test/bench
      BenchmarkFib-6           3888090               307 ns/op
      PASS
      ok      test/bench      1.850s
    • View memory allocation information: go test -bench=. -benchmem
      $ go test -bench=. -benchmem
      goos: windows
      goarch: amd64
      pkg: test/bench
      BenchmarkFib-6           3897542               307 ns/op               0 B/op          0 allocs/op
      PASS
      ok      test/bench      1.858s
    • Generate CPU information: go test -bench=. -benchmem -cpuprofile prof.cpu
      • go tool pprof bench.test.exe prof.cpu
    • Generate memory information: go test -bench=. -benchmem -memprofile prof.mem
      • go tool pprof bench.test.exe prof.mem
    • Generate all information: go test -bench=".*" -benchtime=1000x -cpuprofile cpu.profile -benchmem -memprofile=mem.profile -blockprofile=block.profile -trace trace.out -mutexprofile mutex.out

2. Interpreting Results

Interpreting Go Benchmark Results | Shuiyue Huaer

3. References

How to write benchmarks in Go | Dave Cheney Top 10 Common Go Mistakes, Part 2: Benchmark Performance Testing Pitfalls - Juejin benchmark | High Performance Go | GeekTutu benchmarking - What does allocs/op and B/op mean in go benchmark? - Stack Overflow Interpreting Go Benchmark Results | Shuiyue Huaer Golang Performance Optimization Analysis: benchmark with pprof - Jiujian - cnblogs

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub