← Back to Node.js, page 4

nodejs-0064 · Medium mid

How do you capture a CPU profile of a running Node.js program and find the hottest function?

Use node --cpu-prof to write a .cpuprofile file when the process exits, or start the profiler on demand through the inspector module (Profiler.start and Profiler.stop). Open the file in Chrome DevTools or VS Code to see a flame graph, and sort by self time to find the function that burns the CPU.

Full answer

A CPU profile samples the call stack about every millisecond. The more samples a function appears in, the more time it used.

Ways to get one:

  • node --cpu-prof app.js writes a file such as CPU.2026....cpuprofile when the process ends. Options: --cpu-prof-dir, --cpu-prof-interval.
  • node --inspect and the Performance or Profiler panel in DevTools, for a live process.
  • Code: inspector.Session, session.post('Profiler.enable'), 'Profiler.start', then 'Profiler.stop', which returns the profile object. This is how you build an endpoint that records 10 seconds of a staging process.
  • Tools built on the same data: 0x, clinic flame, and the VS Code profile viewer.

Reading a profile:

  • Self time: time inside the function body only.
  • Total time: self time plus callees.
  • A wide bar at the top of a flame graph is a hot function. Wide bars lower down are callers that spend time in children.
  • Look for JSON.parse and stringify, regular expressions, synchronous crypto, sorting, string concatenation in loops, and garbage collection ((garbage collector) entries).
  • (idle) and (program) entries are not your code. A mostly idle profile means the problem is waiting, not CPU.

Always profile with realistic load, with the same Node version and build, and compare before and after a change. A profile of an idle process is useless.

The profile format: nodes (call frames with ids), samples (a node id per sample) and timeDeltas (microseconds between samples). The snippet below aggregates self time by function name from that data.

javascript
const inspector = require('node:inspector/promises');

function checksumOfMarks(rounds) {
  let total = 0;
  for (let i = 0; i < rounds; i++) total += (i * 31) % 7;
  return total;
}

function quickHelper() {
  return Array.from({ length: 1000 }, (_, i) => i).length;
}

async function main() {
  const session = new inspector.Session();
  session.connect();
  await session.post('Profiler.enable');
  await session.post('Profiler.start');

  checksumOfMarks(150_000_000); // the hot code
  quickHelper();

  const { profile } = await session.post('Profiler.stop');
  session.disconnect();

  // Add up self time (microseconds) per function name.
  const byId = new Map(profile.nodes.map((node) => [node.id, node]));
  const selfTime = {};
  profile.samples.forEach((id, i) => {
    const name = byId.get(id).callFrame.functionName || '(anonymous)';
    selfTime[name] = (selfTime[name] || 0) + profile.timeDeltas[i];
  });
  const [hottest] = Object.entries(selfTime).sort((a, b) => b[1] - a[1])[0];

  console.log('profile has samples:', profile.samples.length > 0);
  console.log('hottest function by self time:', hottest);
  console.log('quickHelper used less time than the hot function:', (selfTime.quickHelper || 0) < selfTime.checksumOfMarks);
}

main();

The profile data lists call frames and samples, so the script can find the hottest function without a UI. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): profile has samples: true hottest function by self time: checksumOfMarks quickHelper used less time than the hot function: true

Key points

  • Profiles sample call stacks, and self time shows hot functions.
  • --cpu-prof writes a file on exit. The inspector module records on demand.
  • (idle) means waiting, not CPU work.
  • Profile under realistic load and measure again after the fix.

Common mistakes

  • Profiling a process that is idle or has no load.
  • Reading total time as if it were self time.
  • Profiling a debug or different build and changing the wrong thing.
  • Optimising a function that uses 1 percent of the time.

Follow-ups

  • What is the difference between a CPU profile and a heap snapshot?
  • How do you profile code that runs in a worker thread?
  • What does a wide (garbage collector) bar mean?

Tips

  • Say 'self time versus total time' without being asked.
  • Name a way to capture a profile on demand, to show practical experience.
  • Describe the before and after comparison.