Performance Benchmarks and pprof Profiling
Write benchmarks, generate CPU and memory profiles, and analyze performance bottlenecks with pprof.
Prerequisites
- -Go 1.21+ installed
- -graphviz installed (for pprof visualization)
Steps
Write a benchmark function
Create a benchmark test file following Go naming conventions.
Run benchmarks
Execute benchmarks with memory allocation statistics.
Use -count=5 for statistically meaningful results. Use benchstat to compare multiple runs.
Generate a CPU profile
Run benchmarks and produce a CPU profile for analysis.
Analyze the CPU profile interactively
Open pprof to explore hotspots in the CPU profile.
The web UI shows flame graphs, call graphs, and source-level annotations. Focus on the widest bars in the flame graph.
Generate and analyze memory profile
Profile heap allocations to find memory-intensive code paths.
Memory profiles show allocations, not current memory usage. Look for high alloc_objects to find GC pressure.
Compare benchmarks with benchstat
Use benchstat to compare two benchmark runs and detect regressions.
Install benchstat with: go install golang.org/x/perf/cmd/benchstat@latest
Full Script
FAQ
Discussion
Loading comments...