How do you use perf and flame graphs for performance analysis on Linux?

Answer

perf is Linux's built-in performance analysis tool backed by hardware performance counters. perf stat ./myapp records CPU metrics (instructions, cache misses, context switches) for one run. perf record -g ./myapp samples the call graph at 100Hz; perf report shows an interactive annotated hot-path breakdown. For a flame graph (a hierarchical visualization of where CPU time is spent): run perf record -g -p PID, then perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg using Brendan Gregg's tools. The width of each bar represents the proportion of time spent — wide bars at the top of the call stack are the hottest functions to optimize. Flame graphs are the industry standard for CPU profiling on Linux production systems.