Stage 1 · Code
Testing & Debugging in Go
pprof Basics
Collect CPU, memory, and goroutine profiles to find exactly where your program spends time and allocates memory.
What is Profiling?
A profile is a statistical sample of where your program spends time (CPU) or where it allocates memory (heap). Profiling tells you exactly which functions are expensive — so you optimize the right thing.
Most performance problems are in 1–3% of the code. Guessing wastes time and often makes things worse. Always profile first — then optimize the function at the top of the flame graph.
CPU Profiling
Add net/http/pprof to expose profiles over HTTP, or use runtime/pprof directly. Then use go tool pprof to analyze.
# Collect 30 seconds of CPU data from a running server
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
# Inside pprof interactive shell:
(pprof) top10 # show top 10 hot functions
(pprof) web # open flame graph in browser (needs graphviz)
(pprof) list FunctionName # show annotated source for a function
(pprof) quit
# Profile a benchmark and view results
go test -bench=BenchmarkMyFunc -cpuprofile=cpu.out ./...
go tool pprof cpu.out
# Or use bench with memory profiling
go test -bench=. -memprofile=mem.out ./...
go tool pprof mem.outMemory Profiling
The heap profile shows where allocations happen. High alloc_objects means a function allocates frequently — consider reusing objects with sync.Pool or pre-allocating slices.
# Capture heap snapshot from a running server
go tool pprof http://localhost:6060/debug/pprof/heap
(pprof) top # top allocating functions
(pprof) inuse_space # current live allocations
(pprof) alloc_space # all allocations since startup
(pprof) web # flame graphGoroutine Profiles
The goroutine profile shows all running goroutines and their stack traces. A goroutine leak (count growing over time) shows up clearly here.
# Goroutine profile — all running goroutines
curl -s http://localhost:6060/debug/pprof/goroutine?debug=1 | head -50
# Or via pprof tool
go tool pprof http://localhost:6060/debug/pprof/goroutine
# Block profile — goroutines waiting on channel/mutex
go tool pprof http://localhost:6060/debug/pprof/block
# Mutex contention profile
go tool pprof http://localhost:6060/debug/pprof/mutexFor production services, consider tools like Pyroscope or Google Cloud Profiler that collect profiles continuously with very low overhead. Profiles captured during an incident are often the fastest path to root cause.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.