Flame graph
- Node.js course
- Expert
- Lesson 37/47
- 5 min
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.
Practice 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)).
Starter code
// Write the flameWidth function
// Divide samples by total, multiply by 100, round, return as percent
// Print calls (25, 100) and (50, 100)
// write hereSample solution
function flameWidth(samples, total) {
const pct = Math.round((samples / total) * 100);
return pct + '%';
}
console.log(flameWidth(25, 100));
console.log(flameWidth(50, 100));Expected output
25% 50%
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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) Correct answer
- Disk gecikmesini
Explanation: Width shows time spent, that is the sample count.
2 Complete the percent return
return pct + '____';
return pct + '%';
Explanation: The percent sign completes the string.
3 Match each piece to its role
| Term | Meaning |
|---|---|
samples |
Sample count |
Math.round |
Rounds |
total |
Total samples |
'%' |
Percent sign |