pprof
pprof is Go's profiling toolchain: the runtime/pprof and net/http/pprof packages write profiles, and the go tool pprof command visualizes them. Heap, CPU, goroutine, mutex, and block profiles are the usual views.
Detailed Explanation
A program is slow or large and you should not guess. A CPU profile samples the call stack many times a second so you see where time is spent. A heap profile samples allocations so you see where bytes are born. A goroutine profile is a snapshot of every stack, which is how you find a leak of stuck workers.
How you collect. In tests, go test -cpuprofile=cpu.out -memprofile=mem.out. In a server, import _ "net/http/pprof" and expose /debug/pprof/ on an internal port. curl the heap or profile?seconds=30 endpoints. Do not expose pprof on the public internet; it is a denial-of-service and an information leak.
How you read. go tool pprof cpu.out then top, list, web. go tool pprof -http=:0 mem.out opens a browser. For heap, compare inuse_space (live) vs alloc_space (cumulative allocations). A high alloc_space with low inuse is allocation churn (GC work). A high inuse is a leak or a large live set.
Mutex and block. -mutexprofile and /debug/pprof/mutex show lock contention. Block profiles show time waiting on channels and selects. Enable them with runtime.SetMutexProfileFraction and SetBlockProfileRate — they are off or sampled by default because they cost.
What it costs. CPU profiling at the default rate is a few percent. Heap sampling (GODEBUG=gctrace=1 is different) is cheap at the default MemProfileRate. Continuous production profiling is done by many shops; still keep the endpoints internal.
Code Examples
package main
import (
"net/http"
_ "net/http/pprof"
)
func main() {
// Bind to localhost in real services.
go http.ListenAndServe("localhost:6060", nil)
select {}
}go test -bench=. -cpuprofile=cpu.out -memprofile=mem.out
go tool pprof -http=:0 mem.outimport "runtime/pprof"
func writeCPU(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
return err
}
defer pprof.StopCPUProfile()
return work()
}Common Gotchas
Public `/debug/pprof` is a security bug
bind internally and require auth.
Heap `alloc_space` is not a leak
look at `inuse_space` for live growth.
A 30s CPU profile of an idle server is empty
load the process while you record.
`pprof` files are binary
commit them only if you mean to; they can contain paths and function names.