Course contentsShow
← Software Engineering
Lesson 1196 of 1,93336. Performance EngineeringFree lesson

CPU Profiling and Flame Graphs

Measuring CPU time consumption across functions and visualizing call stacks with flame graphs to identify hotspots.

CPU Profiling and Flame Graphs

You'll learn how to measure where your program spends CPU time and visualize it to find performance bottlenecks.

What is CPU Profiling?

CPU profiling measures how much processor time each function in your program consumes. Instead of guessing which code is slow, a CPU profiler samples your running program thousands of times per second, recording which function was executing at each moment. The result is a detailed breakdown: "Function A used 40% of CPU time, Function B used 25%," and so on.

Think of it like taking random snapshots of a busy kitchen throughout dinner service. If 60% of your photos show the chef chopping vegetables, that's clearly where most time is spent—even if other tasks happen too.

Understanding Flame Graphs

A flame graph is a visualization that shows the entire call stack hierarchy and how much CPU time each function consumed. It's called a "flame" graph because it resembles fire rising upward:

  • Width represents CPU time consumed (wider = more time)
  • Height represents call stack depth (bottom = entry points, top = leaf functions)
  • Boxes are stacked to show which function called which

The x-axis doesn't represent time order—it's alphabetical or arbitrary. What matters is width. If you see a wide box, that's a hotspot: code consuming significant CPU resources.

Finding the Bottlenecks

Flame graphs let you instantly spot problems. A wide box at the top means you're spending lots of time in a specific leaf function. A wide box at the bottom that branches into many narrow children suggests the parent function itself is expensive, not its callees.

This visualization works perfectly with both sampling and instrumentation profilers you learned about previously—it's simply the clearest way to present that call-stack data.

Key Takeaway: CPU profiling measures where your program spends processor time; flame graphs visualize the call hierarchy and CPU consumption by width, making performance hotspots immediately visible.