runtime/pprof

Guided tour · Runtime & Debug · pkg.go.dev →

Write CPU, heap, block, mutex, goroutine profiles. Analyze with `go tool pprof`.

CPU profile

Start / Stop

f, _ := os.Create("cpu.pprof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()

// ... workload ...

Heap / goroutine / other profiles

Lookup + WriteTo

f, _ := os.Create("heap.pprof")
pprof.Lookup("heap").WriteTo(f, 0)

// others: "goroutine", "allocs", "block", "mutex", "threadcreate"

Labels

Tag goroutines for profiling

pprof.Do(ctx, pprof.Labels("endpoint", "/users"), func(ctx context.Context) {
    serve(ctx)
})

Analyze

go tool pprof

go tool pprof cpu.pprof
(pprof) top
(pprof) web
(pprof) list funcName