Node.js
Flame graph
Learn flame graphs and CPU profiling.
What is a flame graph?
A flame graph visualizes CPU profiling output. The horizontal axis is the sample count, the vertical axis is the call stack depth. Each function is drawn as a rectangle; its width shows how much time it consumed.
A flameWidth(samples, total) function models this width: it divides the sample count by the total, multiplies by 100 and returns it as a percent. Example: flameWidth(25, 100) returns '25%'. Math.round rounds the result to an integer. This model shows the core calculation of a flame graph; real tools (0x, clinic.js) build full graphs from thousands of samples, but each box's width follows the same formula.
Stack depth
The vertical axis of a flame graph is stack depth. Each row is a call frame; the one above called the one below. A narrow tall tower signals deep recursion or a long call chain.
The width shows how long that frame was seen. flameWidth(25, 100) returns '25%'; this means the function was on the stack in a quarter of all samples. When reading a flame graph you first find the widest box; that is where optimization pays the most. Stack depth explains how you reached that function. Together the two axes locate the bottleneck by both position and size.
Exercise Write the flame width function
Write function flameWidth(samples, total). Define const pct = Math.round((samples / total) * 100). Return pct + '%'. Print console.log(flameWidth(25, 100)) and console.log(flameWidth(50, 100)).
Show example solution
function flameWidth(samples, total) {
const pct = Math.round((samples / total) * 100);
return pct + '%';
}
console.log(flameWidth(25, 100));
console.log(flameWidth(50, 100));
Test yourself
-
What does a box's width show in a flame graph?
flameWidth(25, 100)
- The call depth
- The memory usage
- The time spent (sample count)
- Disk gecikmesini
Show answer
The time spent (sample count) — Width shows time spent, that is the sample count.
-
Complete the percent return
return pct + '____';
Show answer
return pct + '%';
-
Match each piece to its role
- samples
- Sample count
- Math.round
- Rounds
- total
- Total samples
- '%'
- Percent sign
Next lesson: V8 flags