CodeBlanks Logo Icon CodeBlanks

CPU profiling

Learn CPU profiling and flame graphs.

CPU profiling

CPU profiling finds which functions consume your app's time. Node.js uses the V8 engine's built-in profiler. There are two paths: start with the --cpu-prof flag, or use the inspector module to profile at runtime.

The inspector module gives access to the Chrome DevTools Protocol. You open a session with new Session(), start the profiler, stop it, and read the result. This is a powerful tool for finding bottlenecks in production.

PerformanceObserver

PerformanceObserver is a class in the perf_hooks module. It catches performance entries (PerformanceEntry) live. You create it with new PerformanceObserver(cb) and start it with .observe().

For example you place performance.mark("start") and performance.mark("end"), then measure the gap with performance.measure("label", "start", "end"). The observer catches these measurements and passes them to the callback. This is a declarative, W3C-standard measurement method.

Practice Log the type of PerformanceObserver

Import PerformanceObserver from perf_hooks. Log typeof PerformanceObserver.

Starter code

index.js
// import the module, get the observer

// log its type

Sample solution

index.js
const { PerformanceObserver } = require("perf_hooks");
console.log(typeof PerformanceObserver);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which built-in module is used for CPU profiling?

  • fs
  • url
  • path
  • inspector Correct answer

Explanation: The inspector module gives access to the Chrome DevTools Protocol.

2 Match each piece to its role

Term Meaning
inspector Profiling
Session Connection
PerformanceObserver Catches entries
profiler CPU profile

3 Complete the module name

Question
const { Session } = require("____")
Answer
const { Session } = require("inspector")

Explanation: The inspector module loads as 'inspector'.

All lessons in Advanced