Flame Graph
What is a flame graph?
A flame graph is a chart of where a program spends its time, built from many samples of its call stack. Each rectangle (a frame) is a function, stacked on top of the function that called it. A frame's width is the share of samples in which that function was on the stack, so the widest frames cost the most.

A flame graph of 100,000 CPU samples from a web server with three routes (sample data). Try the interactive version.
- Each frame is a function. The frame below it is its caller; the frames on top are the functions it called.
- Width is the share of samples, not time. Frames are usually sorted alphabetically, so left to right means nothing.
- Look for wide plateaus: wide frames with nothing on top. That is the code that was actually running, and the place to start optimising.
- A flame chart looks the same but has time on the x-axis. Use it to see the order of events; use a flame graph to see totals.
- Colours are usually random warm shades. If a tool gives them a meaning, such as the kind of code, it says so in a key.
How to read a flame graph
Read a flame graph from the bottom up to follow a call path, and across to compare costs.
- Start at the bottom. The bottom frame is the root, often the whole program or "all" samples, and it spans 100%. Each row up is one level deeper in the call stack.
- Compare widths. A frame's width is the share of samples in which that function was on the stack, either running its own code or waiting on a function it called. A frame twice as wide was seen twice as often.
- Find the plateaus. The top edge of the graph is what the CPU was actually running. A wide frame with nothing above it (a plateau) is a function that spent its time in its own code.
- Read the gaps. If a frame is wider than all the frames on top of it, the uncovered part is its self time: samples where it was running its own code rather than a callee.
- Ignore left and right. In most flame graphs, siblings are sorted alphabetically, so a frame's position says nothing about when it ran. For the order of events, use a flame chart.
- Check the colours. In the original flame graphs, colours are random warm shades chosen to tell frames apart. Some tools colour by language, by library or by user versus kernel code; read the tool's key.
Then zoom in. Real profiles have thousands of frames, and the narrow ones only get a readable label once you click into their parent.
Worked example: a slow report endpoint
The flame graph at the top of this page is a CPU profile of a Node.js web server. A profiler sampled the call stack 100,000 times while the server handled three kinds of request: a report, a search and an export. Like a real profile, it has thousands of frames: most are small helper calls in libraries and the runtime, which make the thin spikes. The routes sit side by side on top of router.handle. The report route, handleReport, is by far the widest at 67.6% of samples, against 12.4% for handleSearch and 7.8% for handleExport. Its tower breaks down like this:
| Frame | On the stack | Self time | What it tells you |
|---|---|---|---|
loadData | 33.0% | 0.0% | Almost half of the report's time goes on loading the data, not processing it |
parseCSV | 28.8% | 0.2% | Most of that is parsing the text file; reading it (readFile) is only 3.9% |
parseNumber | 15.1% | 0.3% | Turning text into numbers is the single biggest cost inside the parser |
parseFloat | 11.2% | 11.2% | The widest plateau: the CPU is running this one built-in in one sample in nine |
renderReport | 16.8% | 0.1% | Building the response costs more than the statistics |
computeStats | 15.3% | 0.0% | Statistics, mostly sorting: sortValues is 9.5%, of which its compare callback is 8.0% |
Number.toFixed | 3.5% + 2.0% | 3.5% + 2.0% | Formatting numbers appears in two towers (the table and the chart), 5.5% in all |
gc | 4.9% | 0.0% | The garbage collector, beside main rather than under it |
Notice that most frames have almost no self time: they spend it in the functions they call. That is normal, and it is why you read a flame graph from the plateaus at the top of each tower, not from the wide frames at the bottom.
Three conclusions follow. First, the fastest win is in parsing, not in the statistics code a developer might suspect: storing the data as numbers, or caching the parsed result, removes up to 15% of all CPU work (parseNumber), and more if the whole parse goes. Second, the sort is the next target, for example by sorting once and reusing the result. Third, look across towers as well as up them: Number.toFixed, deflate and parseFloat each appear in more than one place, and a function split across several narrow towers can cost more than it looks. Hover over a frame in the live chart to see its total across all its call paths.
A CPU flame graph shows only time spent running. If the export also waits on its database, that waiting doesn't appear here (see off-CPU flame graphs below).
How to describe a flame graph
Use this template when you report what a flame graph shows:
[Function] is on the stack in [x]% of samples, mostly through [child] ([y]%). The widest plateau is [function] at [z]%, so [what to change] would save up to [z]% of CPU time.
For example: "loadData is on the stack in 33% of samples, mostly through parseCSV (28.8%). The widest plateau is parseFloat at 11%, so storing the data as numbers instead of text would save up to 15% of CPU time, counting the rest of parseNumber."
Flame graph vs flame chart
A flame chart draws the same stacked frames, but with time on the x-axis. Every call appears where it happened, so a function called five times shows up as five separate blocks. The Main track of the Chrome DevTools Performance panel is a flame chart.
A flame graph merges identical stacks and sorts them alphabetically, so each function appears once in each call path, as wide as its total. That throws away the order of events but makes the expensive code stand out, however many times it was called.
| Flame chart | Flame graph | |
|---|---|---|
| X-axis | Time | Share of samples (sorted A to Z) |
| Repeated calls | Shown separately, in order | Merged into one frame |
| Best for | When things happened: long tasks, jank, the sequence of a request | Where time went overall: the hottest code paths |
| Typical tools | Browser DevTools performance panels, tracing tools | Sampling profilers for servers, browsers and native code |
Types of flame graph
The flame graph layout works for any measurement that can be added up along a call stack. The most common types are:
| Type | Width means | Use it to find |
|---|---|---|
| CPU flame graph (on-CPU) | Samples while the code was running on a CPU | Code that burns CPU time |
| Off-CPU flame graph | Time spent blocked: waiting for disk, network, locks or sleep | Why a request is slow when the CPU is idle |
| Memory (allocation) flame graph | Bytes or objects allocated | Code that allocates the most memory or causes garbage collection |
| Differential flame graph | The same layout, coloured red or blue by the change between two profiles | What got slower or faster after a change |
| Icicle graph | The same as a flame graph, drawn upside down with the root at the top | The same things; some tools prefer this layout |
Related layouts show the same hierarchy differently. A sunburst chart bends the rows into rings, and its icicle chart is the same idea for any nested data. A treemap nests the rectangles inside each other.
How flame graphs are made
Flame graphs were created by Brendan Gregg in 2011 while he was investigating a MySQL performance problem, and he published the original scripts as open source. Most tools now follow the same three steps:
- Sample the stack. A sampling profiler interrupts the program many times a second and records the call stack each time. Gregg's examples sample at 99 Hz rather than 100 Hz so the samples don't line up with work that runs on a regular timer.
- Fold the stacks. Identical stacks are merged and counted. The common text form, "folded stacks", puts one stack per line with frames separated by semicolons, then the count:
main;handleRequest;loadData;parseCSV 25. - Draw the graph. Each folded stack becomes a column of frames. Shared prefixes are merged, siblings are sorted, and each frame gets a width in proportion to its samples.
Profilers that output flame graphs, or folded stacks you can turn into one, include perf on Linux, async-profiler for Java, py-spy for Python, cargo flamegraph for Rust, pprof for Go and the Firefox Profiler for web pages. The more samples you collect, the more you can trust the narrow frames: a frame seen in 3 samples out of 1,000 could easily be noise. The example on this page uses 100,000.
When to use a flame graph
Use a flame graph when you want to know which code paths account for most of a cost, across many calls and many samples. Typical uses:
- CPU profiling of servers, desktop apps, games and browser code;
- finding what allocates memory or triggers garbage collection;
- comparing two builds or two configurations with a differential flame graph;
- any other hierarchy of costs, such as disk usage by folder or cloud spend by service.
| Chart | Best for |
|---|---|
| Flame graph | Which call paths account for most of the samples, merged across every call |
| Flame chart or timeline chart | When each call or event happened, and in what order |
| Bar chart of the top functions | A quick ranked list of self time, without the call paths |
| Sunburst chart or treemap | Shares of a total in nested levels, for a general audience |
Common flame graph mistakes
Most flame graph mistakes come from reading it like an ordinary chart with time on the x-axis.
- Reading the x-axis as time. In a flame graph, left to right is alphabetical. A frame on the left didn't run first, and two neighbouring frames didn't run one after the other.
- Chasing tall towers. Height is only call depth. A deep stack is not a slow one; a wide one is.
- Missing a function that is split up. The same function called from several places appears in several towers, each narrower than its total. Add them up, or use the tool's search or "merge" view, before you rank the costs.
- Optimising the wrong frame. A wide frame low down mostly counts time spent in its callees. Look at the plateaus on top, and at the self time of each frame, before you change code.
- Reading meaning into random colours. Unless the tool has a key, the colours are there only to tell neighbouring frames apart.
- Trusting a short profile. With a few hundred samples, narrow frames are mostly noise. Sample for longer, or while the slow work is repeating.
- Missing the waiting time. A CPU flame graph doesn't show time spent waiting for the disk, the network or a lock. If the CPU was mostly idle, use an off-CPU flame graph or a trace.
- Broken stacks. Missing frame pointers or debug symbols produce truncated stacks and frames labelled with raw addresses. Fix the profiler's settings before drawing conclusions.
How to create a flame graph in JavaScript, React or Angular
SciChart.js draws flame graphs with a rectangle series: one rectangle per frame, with its share of samples on the x-axis and its stack depth on the y-axis. Drawing with WebGL keeps a profile with thousands of frames smooth to zoom. The chart below is the web server profile from the worked example: 100,000 samples in about 8,000 frames, up to 46 levels deep. Hover over a frame for a tooltip with its call path, samples, self time and share of its caller. Click a frame to zoom into it: it fills the width and its rows grow tall enough for the function names. Then use Zoom out to step back to its caller and Reset (or double-click) to see the whole profile again. You can also scroll to zoom and drag to pan. As you zoom, function names appear in frames that were too narrow to label.
Here is the code for this chart:
- JavaScript
- React
- Angular
// Create a JavaScript flame graph with SciChart.js: one rectangle per stack frame,
// width = share of samples, height = stack depth, with an HTML tooltip and click-to-zoom
const {
SciChartSurface,
NumericAxis,
FastRectangleRenderableSeries,
XyxyDataSeries,
BoxAnnotation,
CustomChartModifier2D,
DpiHelper,
EColumnMode,
EColumnYMode,
EAutoRange,
EXyDirection,
NumberRange,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomPanModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
const { wasmContext, sciChartSurface } = await SciChartSurface.create(divElementId, {
theme: new SciChartJsNavyTheme()
});
// 1. Merge the folded stacks into a tree. Each node counts the samples where its function was on the stack
const root = { name: "all", total: 0, self: 0, children: {} };
getProfileData()
.trim()
.split("\n")
.forEach((line) => {
const splitAt = line.lastIndexOf(" ");
const samples = Number(line.substring(splitAt + 1));
let node = root;
node.total += samples;
line.substring(0, splitAt)
.split(";")
.filter(Boolean)
.forEach((name) => {
node.children[name] = node.children[name] || { name, total: 0, self: 0, children: {} };
node = node.children[name];
node.total += samples;
});
node.self += samples;
});
// 2. Lay out the frames: the root spans 0 to 100% at the bottom, and each child sits on top of its parent,
// with a width in proportion to its samples. Siblings are sorted by name, as in most flame graphs:
// left to right means nothing, so the x-axis is not time.
// Colours are warm shades picked from the function name, so the same function has the same colour
// everywhere. They only tell neighbouring frames apart; the tooltip says what kind of code each frame is.
const warmColours = [
"#E8553D", "#EE6A3A", "#F27E36", "#F59234", "#F6A535", "#F8B83C", "#F9C94A", "#E9473F",
"#F0743F", "#F49A45", "#F6B24F", "#F8C65C", "#E3603A", "#EC8A3B", "#F3AD40", "#F7D06A"
];
const colourIndex = (name) => {
let hash = 0;
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;
return name === "all" ? -1 : Math.abs(hash) % warmColours.length;
};
const colourOf = (name) => (colourIndex(name) < 0 ? "#9AA3B5" : warmColours[colourIndex(name)]);
// A darker outline of the same hue keeps neighbouring frames apart without hiding thin ones
const darker = (hex) => `#${[1, 3, 5].map((i) => Math.round(parseInt(hex.substr(i, 2), 16) * 0.72).toString(16).padStart(2, "0")).join("")}`;
const builtIns = ["parseFloat", "decodeURIComponent", "deflate"];
const kindOf = (name, parent) =>
name === "all"
? "All samples"
: name === "gc" || (parent && parent.kind === "Garbage collector")
? "Garbage collector"
: name.includes(".") || builtIns.includes(name)
? "Built-in or library"
: "Your code"; // shown in the tooltip
const percent = (samples) => (samples / root.total) * 100;
const formatPercent = (value) => `${value < 10 ? value.toFixed(1) : value.toFixed(0)}%`;
// A function can appear in several call paths (several towers). Add up its samples across all of them,
// skipping calls nested inside another call of the same function so recursion isn't counted twice
const allPaths = {};
const sumByName = (node, open) => {
if (!open.includes(node.name)) {
allPaths[node.name] = allPaths[node.name] || { samples: 0, towers: 0 };
allPaths[node.name].samples += node.total;
allPaths[node.name].towers += 1;
}
Object.values(node.children).forEach((child) => sumByName(child, [...open, node.name]));
};
sumByName(root, []);
const frames = [];
const layout = (node, start, depth, parent) => {
const frame = {
isSelected: false, // the frame object is also the rectangle's metadata
name: node.name,
start,
end: start + percent(node.total),
samples: node.total,
depth,
parent,
kind: kindOf(node.name, parent),
top: depth, // the deepest row in this frame's subtree, for zooming
label: node.name,
html: ""
};
// The HTML for this frame's tooltip
const path = [];
for (let p = parent; p && p.name !== "all"; p = p.parent) path.unshift(p.name);
const shownPath = path.length > 3 ? ["…", ...path.slice(-3)] : path;
const share = percent(node.total);
const colour = colourOf(node.name);
const everywhere = allPaths[node.name];
const muted = "color: #9AA3B5";
frame.html = `
<div style="font-weight: 600; font-size: 15px; color: #FFFFFF">${node.name}</div>
<div style="font-size: 12px; ${muted}; margin: 2px 0 8px">${shownPath.join(" › ") || "the whole profile"}</div>
<div style="height: 6px; border-radius: 3px; background: #2A3550; margin-bottom: 8px">
<div style="height: 6px; border-radius: 3px; width: ${Math.max(share, 1)}%; background: ${colour}"></div>
</div>
<div style="display: grid; grid-template-columns: auto auto; gap: 3px 14px">
<span style="${muted}">On the stack</span>
<span>${formatPercent(share)} · ${node.total.toLocaleString("en-GB")} samples</span>
<span style="${muted}">Self time</span>
<span>${formatPercent(percent(node.self))} · ${node.self.toLocaleString("en-GB")} samples</span>
${parent ? `<span style="${muted}">Share of caller</span><span>${Math.round((node.total / parent.samples) * 100)}% of ${parent.name}</span>` : ""}
${everywhere.towers > 1 ? `<span style="${muted}">All call paths</span><span>${formatPercent(percent(everywhere.samples))} in ${everywhere.towers} places</span>` : ""}
<span style="${muted}">Kind</span>
<span><span style="color: ${colour}">■</span> ${frame.kind}</span>
</div>`;
frames.push(frame);
let childStart = start;
Object.keys(node.children)
.sort()
.forEach((name) => {
const child = node.children[name];
const childFrame = layout(child, childStart, depth + 1, frame);
frame.top = Math.max(frame.top, childFrame.top);
childStart += percent(child.total);
});
return frame;
};
layout(root, 0, 0, null);
const maxDepth = Math.max(...frames.map((frame) => frame.depth));
// X axis: % of all samples. Y axis: stack depth, one row per level, root at the bottom
const xAxis = new NumericAxis(wasmContext, {
axisTitle: "Share of samples (not time)",
labelPostfix: "%",
labelPrecision: 0,
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(0, 100),
visibleRangeLimit: new NumberRange(0, 100),
drawMinorGridLines: false
});
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Stack depth",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-5, maxDepth + 3), // room below the root for the watermark, above for the buttons
drawLabels: false,
drawMajorTickLines: false,
drawMinorTickLines: false,
drawMajorGridLines: false,
drawMinorGridLines: false,
drawMajorBands: false
})
);
// 3. One rectangle series per colour: x to x1 is the frame's share of samples, y to y1 its row
const frameSeries = [-1, ...warmColours.keys()].map((index) => {
const ofKind = frames.filter((frame) => colourIndex(frame.name) === index);
const series = new FastRectangleRenderableSeries(wasmContext, {
dataSeries: new XyxyDataSeries(wasmContext, {
xValues: ofKind.map((frame) => frame.start),
x1Values: ofKind.map((frame) => frame.end),
yValues: ofKind.map((frame) => frame.depth + 0.95),
y1Values: ofKind.map((frame) => frame.depth + 0.05),
metadata: ofKind
}),
columnXMode: EColumnMode.StartEnd, // x = left edge, x1 = right edge
columnYMode: EColumnYMode.TopBottom, // y = top of the frame, y1 = bottom
fill: index < 0 ? "#9AA3B5" : warmColours[index],
stroke: darker(index < 0 ? "#9AA3B5" : warmColours[index]),
strokeThickness: 1,
// The function name, written inside its frame
dataLabels: {
color: "#1C1C1C",
style: { fontSize: 12, fontFamily: "Arial" },
metaDataSelector: (frame) => frame["label"]
}
});
sciChartSurface.renderableSeries.add(series);
return { series, frames: ofKind };
});
// 4. Fit each name to its frame as you zoom: shorten it, or hide it in frames too narrow to read
const yAxis = sciChartSurface.yAxes.get(0);
const fitLabels = () => {
const visible = xAxis.visibleRange;
const view = sciChartSurface.seriesViewRect;
const plotWidth = view ? view.width / DpiHelper.PIXEL_RATIO : 800;
const rowHeight = view ? view.height / DpiHelper.PIXEL_RATIO / yAxis.visibleRange.diff : 10;
frames.forEach((frame) => {
if (rowHeight < 14) {
frame.label = ""; // rows too thin for text: click a frame to zoom in and make them taller
return;
}
const left = Math.max(frame.start, visible.min);
const right = Math.min(frame.end, visible.max);
const pixels = ((right - left) / (visible.max - visible.min)) * plotWidth;
const maxChars = Math.floor((pixels - 6) / 7); // about 7 px per character at 12 px Arial; under 5, hide it
frame.label = maxChars < 5 ? "" : frame.name.length <= maxChars ? frame.name : `${frame.name.substring(0, maxChars - 2)}..`;
});
};
xAxis.visibleRangeChanged.subscribe(fitLabels);
yAxis.visibleRangeChanged.subscribe(fitLabels);
let fittedToLayout = false;
sciChartSurface.rendered.subscribe(() => {
// Once the chart has been laid out, fit the labels to the real plot width
if (!fittedToLayout && sciChartSurface.seriesViewRect) {
fittedToLayout = true;
fitLabels();
sciChartSurface.invalidateElement();
}
});
fitLabels();
// 5. Zoom: click a frame to fill the width with it and show its subtree tall enough to label,
// "Zoom out" goes to its caller, "Reset" shows everything.
// HTML buttons and a breadcrumb sit over the top-left corner of the chart.
const chartRoot = sciChartSurface.domChartRoot;
if (getComputedStyle(chartRoot).position === "static") chartRoot.style.position = "relative";
const toolbar = document.createElement("div");
toolbar.style.cssText =
"position: absolute; top: 10px; left: 12px; z-index: 10; display: flex; align-items: center; gap: 6px; " +
"font: 13px system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; color: #C8D0E0";
const makeButton = (text, title) => {
const button = document.createElement("button");
button.textContent = text;
button.title = title;
button.style.cssText =
"background: #1E2A45; color: #FFFFFF; border: 1px solid #3A4A6B; border-radius: 6px; padding: 4px 10px; " +
"font: inherit; cursor: pointer";
toolbar.appendChild(button);
return button;
};
const zoomOutButton = makeButton("− Zoom out", "Zoom out to the caller");
const resetButton = makeButton("Reset", "Show the whole profile");
const breadcrumb = document.createElement("span");
breadcrumb.style.cssText = "margin-left: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 420px";
toolbar.appendChild(breadcrumb);
chartRoot.appendChild(toolbar);
const allFrame = frames[0];
let focused = allFrame;
const zoomTo = (frame) => {
focused = frame;
xAxis.animateVisibleRange(new NumberRange(frame.start, frame.end), 400);
// Rows: from just below the frame to the top of its subtree, at least 16 rows so labels fit
const bottom = frame === allFrame ? -5 : frame.depth - 0.6;
const top = frame === allFrame ? maxDepth + 3 : Math.min(Math.max(frame.top + 2.4, bottom + 16), maxDepth + 3);
yAxis.animateVisibleRange(new NumberRange(bottom, top), 400);
const path = [];
for (let p = frame; p && p !== allFrame; p = p.parent) path.unshift(p.name);
breadcrumb.textContent = path.length ? path.join(" › ") : "Click a frame to zoom in";
};
zoomOutButton.onclick = () => zoomTo(focused.parent || allFrame);
resetButton.onclick = () => zoomTo(allFrame);
breadcrumb.textContent = "Click a frame to zoom in";
// 6. A custom modifier: hit-tests the frames under the mouse, shows an HTML tooltip and outlines the frame,
// and turns a click (but not a drag, which pans) into a zoom. Double-click resets.
class FlameGraphModifier extends CustomChartModifier2D {
tooltip;
outline;
downPoint;
clickTimer;
constructor() {
super();
this.receiveHandledEvents = true; // still see mouse events that the pan modifier has handled
this.tooltip = document.createElement("div");
this.tooltip.style.cssText =
"position: absolute; z-index: 20; pointer-events: none; display: none; min-width: 230px; max-width: 340px; " +
"padding: 10px 12px; border-radius: 8px; background: rgba(14, 22, 40, 0.95); border: 1px solid #3A4A6B; " +
"box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45); color: #E6EAF2; " +
"font: 13px/1.4 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif";
this.outline = new BoxAnnotation({ isHidden: true, fill: "#FFFFFF22", stroke: "#FFFFFF", strokeThickness: 2 });
}
onAttach() {
super.onAttach();
this.parentSurface.annotations.add(this.outline);
this.parentSurface.domChartRoot.appendChild(this.tooltip);
}
onDetach() {
this.parentSurface?.annotations.remove(this.outline);
this.tooltip.remove();
super.onDetach();
}
// The frame under the mouse, or null. hitTest says whether the point is inside one of a series' rectangles
hitTestFrame(mousePoint) {
for (const { series, frames: ofKind } of frameSeries) {
const hit = series.hitTestProvider.hitTest(mousePoint.x, mousePoint.y);
if (hit.isHit) return ofKind[hit.dataSeriesIndex];
}
return null;
}
hide() {
this.tooltip.style.display = "none";
this.outline.isHidden = true;
}
modifierMouseMove(args) {
super.modifierMouseMove(args);
const frame = this.hitTestFrame(args.mousePoint);
if (!frame) {
this.hide();
return;
}
Object.assign(this.outline, { x1: frame.start, x2: frame.end, y1: frame.depth + 0.05, y2: frame.depth + 0.95 });
this.outline.isHidden = false;
// Place the tooltip beside the mouse, flipped left or up near the right or bottom edge.
// mousePoint is in canvas pixels, so divide by the pixel ratio to get CSS pixels
this.tooltip.innerHTML = frame.html;
this.tooltip.style.borderLeft = `4px solid ${colourOf(frame.name)}`;
this.tooltip.style.display = "block";
const x = args.mousePoint.x / DpiHelper.PIXEL_RATIO;
const y = args.mousePoint.y / DpiHelper.PIXEL_RATIO;
const width = this.tooltip.offsetWidth;
const height = this.tooltip.offsetHeight;
const flipLeft = x + 16 + width > chartRoot.clientWidth;
const flipUp = y + 16 + height > chartRoot.clientHeight;
this.tooltip.style.left = `${flipLeft ? x - width - 16 : x + 16}px`;
this.tooltip.style.top = `${Math.max(4, flipUp ? y - height - 12 : y + 16)}px`;
}
modifierMouseDown(args) {
super.modifierMouseDown(args);
this.downPoint = args.button === 0 ? args.mousePoint : undefined;
}
modifierMouseUp(args) {
super.modifierMouseUp(args);
const down = this.downPoint;
this.downPoint = undefined;
// A click, not a drag: the mouse moved less than a few pixels
if (!down || Math.hypot(args.mousePoint.x - down.x, args.mousePoint.y - down.y) > 5 * DpiHelper.PIXEL_RATIO) return;
const frame = this.hitTestFrame(args.mousePoint);
if (!frame) return;
// Wait briefly, so a double-click resets instead of zooming in twice
clearTimeout(this.clickTimer);
this.clickTimer = setTimeout(() => zoomTo(frame), 250);
}
modifierDoubleClick(args) {
super.modifierDoubleClick(args);
clearTimeout(this.clickTimer);
zoomTo(allFrame);
}
modifierMouseLeave(args) {
super.modifierMouseLeave(args);
this.hide();
}
}
// Scroll to zoom and drag to pan, on the x-axis only, so the rows keep their height
sciChartSurface.chartModifiers.add(
new FlameGraphModifier(),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection })
);
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
FastRectangleRenderableSeries,
XyxyDataSeries,
EColumnMode,
EColumnYMode,
EAutoRange,
EXyDirection,
NumberRange,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
// frames: { name, start, end, depth }, with start and end in % of samples (see steps 1 and 2 in the JavaScript tab)
const frames = getYourFlameGraphFrames();
const maxDepth = Math.max(...frames.map((f) => f.depth));
sciChartSurface.xAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Share of samples",
labelPostfix: "%",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(0, 100),
visibleRangeLimit: new NumberRange(0, 100)
})
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-1.4, maxDepth + 1.6),
drawLabels: false
})
);
// One rectangle per frame: x to x1 is its share of samples, y to y1 its row in the stack
sciChartSurface.renderableSeries.add(
new FastRectangleRenderableSeries(wasmContext, {
dataSeries: new XyxyDataSeries(wasmContext, {
xValues: frames.map((f) => f.start),
x1Values: frames.map((f) => f.end),
yValues: frames.map((f) => f.depth + 0.95),
y1Values: frames.map((f) => f.depth + 0.05),
metadata: frames.map((f) => ({ isSelected: false, label: f.name }))
}),
columnXMode: EColumnMode.StartEnd,
columnYMode: EColumnYMode.TopBottom,
fill: "#F28C38",
stroke: "#1C2A4A",
strokeThickness: 1,
dataLabels: {
color: "#1C1C1C",
style: { fontSize: 13, fontFamily: "Arial" },
metaDataSelector: (md) => md["label"]
}
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showXLine: false, showYLine: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
return { sciChartSurface };
};
export const FlameGraph = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 450 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
FastRectangleRenderableSeries,
XyxyDataSeries,
EColumnMode,
EColumnYMode,
EAutoRange,
EXyDirection,
NumberRange,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
@Component({
selector: "app-flame-graph",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 450px"></scichart-angular>`
})
export class FlameGraphComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
// frames: { name, start, end, depth }, with start and end in % of samples (see steps 1 and 2 in the JavaScript tab)
const frames = getYourFlameGraphFrames();
const maxDepth = Math.max(...frames.map((f) => f.depth));
sciChartSurface.xAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Share of samples",
labelPostfix: "%",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(0, 100),
visibleRangeLimit: new NumberRange(0, 100)
})
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-1.4, maxDepth + 1.6),
drawLabels: false
})
);
// One rectangle per frame: x to x1 is its share of samples, y to y1 its row in the stack
sciChartSurface.renderableSeries.add(
new FastRectangleRenderableSeries(wasmContext, {
dataSeries: new XyxyDataSeries(wasmContext, {
xValues: frames.map((f) => f.start),
x1Values: frames.map((f) => f.end),
yValues: frames.map((f) => f.depth + 0.95),
y1Values: frames.map((f) => f.depth + 0.05),
metadata: frames.map((f) => ({ isSelected: false, label: f.name }))
}),
columnXMode: EColumnMode.StartEnd,
columnYMode: EColumnYMode.TopBottom,
fill: "#F28C38",
stroke: "#1C2A4A",
strokeThickness: 1,
dataLabels: {
color: "#1C1C1C",
style: { fontSize: 13, fontFamily: "Arial" },
metaDataSelector: (md) => md["label"]
}
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showXLine: false, showYLine: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
return { sciChartSurface };
};
}
Key points:
- Profilers often export folded stacks: one call stack per line, with a sample count. Step 1 in the code merges them into a tree, adding each line's count to every function on its stack. Step 2 lays the tree out: each child starts where the previous sibling ended, so siblings fill their parent from left to right.
- A FastRectangleRenderableSeries with an
XyxyDataSeriesdraws each frame fromxtox1(its share of samples) and fromytoy1(its row), set bycolumnXMode: EColumnMode.StartEndandcolumnYMode: EColumnYMode.TopBottom. Each frame's colour is one of 16 warm shades, picked from its function name, so the same function has the same colour in every tower; one series per shade keeps that to 16 series for 8,000 rectangles. - The function names are data labels read from each frame's
metadata. Step 4 shortens or hides them to fit each frame's width in pixels, and hides them all while the rows are too thin for text, whenever either axis range changes, so names appear as you zoom. - The tooltip is plain HTML, styled however you like. A custom modifier (
CustomChartModifier2D, step 6) calls each series'hitTestProvider.hitTest()on every mouse move to find the frame under the mouse, then fills and places a<div>in the chart's root element. DividemousePointbyDpiHelper.PIXEL_RATIOto turn canvas pixels into CSS pixels. - Zooming works on the x-axis only (
xyDirection: EXyDirection.XDirection), so rows keep their height. The same modifier turns a click (but not a drag) intoanimateVisibleRangeto the frame's start and end; the Zoom out and Reset buttons call the same function with the frame's caller or the root.
See it in the demo app: JavaScript Gantt chart · React Gantt chart · Angular Gantt chart, which draws bars from a start to an end value with the same rectangle series.
Go deeper: SciChart.js rectangle series documentation, which draws the frames, and the SciChart.js custom chart modifier documentation for the tooltip and click-to-zoom.
Frequently asked questions
What does a flame graph show?
A flame graph shows where a program spends its time. It is built from many samples of the program's call stack. Each rectangle is a function, stacked on top of the function that called it, and its width is the share of samples in which that function was on the stack. The widest frames with nothing on top of them are the code that used the most CPU.
What is the difference between a flame graph and a flame chart?
Both stack functions on top of their callers, but their x-axes differ. In a flame chart, such as the Main track of the Chrome DevTools Performance panel, the x-axis is time, so every call appears where it happened and repeated calls show as separate blocks. In a flame graph, identical stacks are merged and sorted alphabetically, so the x-axis is the share of samples and each function appears once per call path, as wide as its total.
Why is it called a flame graph?
Because the first flame graphs, created by Brendan Gregg in 2011 to profile CPU usage, were drawn in random warm colours (reds, oranges and yellows) and their jagged towers of stack frames look like flames. The colours usually carry no meaning; some tools use them for the kind of code instead, such as user code, kernel or garbage collection.
How do you generate a flame graph?
Run a sampling profiler while the program does the slow work, so it records the call stack many times a second. Merge identical stacks and count them, usually in the folded-stacks text format (one stack per line, frames separated by semicolons, then a count). Then draw each stack as a column of frames, with widths in proportion to the counts. Many profilers, including perf with Brendan Gregg's FlameGraph scripts, async-profiler, py-spy and the Firefox Profiler, can output flame graphs directly.
What is an icicle graph?
An icicle graph is a flame graph drawn upside down, with the root of the call stack at the top and the frames hanging down. It shows the same data and is read the same way. Some tools offer both, and some use the icicle layout by default so the outermost functions stay at the top of the screen.
How do I make a flame graph in JavaScript?
With SciChart.js, merge your stack samples into a tree, then give each function a start and end (its share of samples, sorted by name) and a row (its stack depth). Draw the frames with a FastRectangleRenderableSeries and an XyxyDataSeries, using EColumnMode.StartEnd and EColumnYMode.TopBottom, and put the function names in the data series' metadata for the labels and tooltips. React (scichart-react) and Angular (scichart-angular) components wrap the same code.
Sources
- Brendan Gregg, Flame Graphs. The inventor's reference page: the origin in 2011, CPU, off-CPU, memory and differential flame graphs, and the FlameGraph scripts.
- Brendan Gregg, The Flame Graph, ACM Queue, vol. 14 no. 2 (2016); also in Communications of the ACM, vol. 59 no. 6. How flame graphs are built and read, including sampling at 99 Hz.
- Chrome for Developers, Performance features reference. The Main track's flame chart, with time on the x-axis and the call stack on the y-axis.
- Wikipedia, Flame graph. Overview, variants and tools.