Benchmarking, Profiling, Tracing

  • Benchmarking - focus on a particular piece of code, allowing measurement of time and/or memory information.

  • Profiling - aggregated data collected through sampling during program (or test) execution. Profiling has no timeline.

  • Tracing - data collected through events occurring during program (or test) execution. They give a chronological view of program's execution with detailed information about heap, GC, goroutines, core usage, ...

Running benchmarks

Run tests:

  • with benchmarks (time) : go test ./fibonacci -bench .

  • with benchmarks (time and memory) : go test ./fibonacci -bench . -benchmem

Profiling benchmarks

Get profiling data from the benchmarks:

  • CPU profiling using -cpuprofile=cpu.out

  • Memory profiling using -benchmem -memprofile=mem.out

go test ./fibonacci \
  -bench BenchmarkSuite \
  -benchmem \
  -cpuprofile=cpu.out \
  -memprofile=mem.out

Viewing profiling data

  • through command line : go tool pprof cpu.out

  • with a browser : go tool pprof -http=localhost:8080 cpu.out

Tracing

go test ./fibonacci \
  -bench BenchmarkSuite \
  -trace=trace.out

go tool trace trace.out

Getting Memory Statistics

  • runtime.ReadMemStats allows you to retrieve memory statistics for the current Go process.

package main

import (
	"fmt"
	"runtime"
)

func main() {
	var memStats runtime.MemStats

	runtime.ReadMemStats(&memStats)

	fmt.Printf("Total allocated memory (in bytes): %d\n", memStats.Alloc)
	fmt.Printf("Heap memory (in bytes): %d\n", memStats.HeapAlloc)
	fmt.Printf("Number of garbage collections: %d\n", memStats.NumGC)
}

Packages:

Resources:

Last updated