Diagnostics

CPU profiling

CPU profiling samples where execution spends time. It helps identify candidate hot paths but does not measure every operation exactly or automatically establish why a service is slow. Use an inspector Session with Profiler.enable, Profiler.start and Profiler.stop on a bounded synthetic workload. Keep profile data private and disconnect after use. A profile describes sampled stacks; short functions may be missed, sampling overhead exists, and waiting on I/O may not appear as a CPU hot spot. Use monotonic measurements and document runtime, workload, warmup, sample count and errors. Compare alternatives only with correctness checks and representative conditions. This lesson validates profile shape and timing mechanics, not a production speed comparison. Do not report a universal speedup from one tiny run or assert exact sample counts. A sampling profile cannot prove every function call occurred. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/inspector.html, https://nodejs.org/docs/latest-v22.x/api/inspector.html.

Formal Syntax & Structure

nodejs syntaxnodejs
session.post("Profiler.start", callback); session.post("Profiler.stop", callback)

Working Example

Example Snippetnodejs
import {Session} from 'node:inspector';import {promisify} from 'node:util';import assert from 'node:assert/strict';const s=new Session();s.connect();const post=promisify(s.post.bind(s));try{await post('Profiler.enable');await post('Profiler.start');let total=0;for(let i=0;i<200000;i++)total+=i%7;const {profile}=await post('Profiler.stop');assert.ok(Array.isArray(profile.nodes)&&profile.nodes.length>0);assert.ok(profile.endTime>=profile.startTime);console.log('profile nodes available');assert.equal(total,599994);console.log('workload checked');}finally{try{await post('Profiler.disable');}finally{s.disconnect();}}
Node.js Reference