Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 133 ยท Processes and Threads

Measuring Performance

Measure Node.js performance with perf_hooks - performance.now, mark and measure, PerformanceObserver, timerify, event loop delay and utilization, plus benchmarking pitfalls and profilers.

"This code feels slow" is not a measurement. Before you optimise anything you need numbers: how long did it take, how often does it run, is the event loop being blocked, where does the time go? Guessing leads to clever changes that make no difference. Measuring leads to the one-line fix that removes 80% of the cost.

Node.js ships a standard toolbox for this: the node:perf_hooks module, which follows the same Performance API as browsers. In this lesson you will use performance.now() for precise timing, mark and measure to label sections of code, PerformanceObserver to collect results without cluttering your logic, timerify to time functions, and the event loop monitors (monitorEventLoopDelay, eventLoopUtilization) that tell you whether the server is healthy. At the end you will see how to profile with the tools that come with Node, and which benchmarking mistakes to avoid.

Timings are different on every machine and every run. The examples in this lesson therefore print facts about the measurements (true when a duration is at least what we expect, names, counts, types) and never the raw milliseconds. On your own computer, print the numbers and watch them change between runs; that variation is itself an important lesson.

performance.now: a monotonic stopwatch

Date.now() returns the wall-clock time. It is the wrong tool for measuring durations because the system clock can jump (time synchronisation, daylight changes, a user setting the clock), and it only has millisecond resolution. performance.now() is a monotonic clock: it never goes backwards, and it returns fractional milliseconds (with microsecond-level detail) since the process started.

Node.js Timing a piece of work with performance.now

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

performance.now() counts from the moment the process started (performance.timeOrigin is that moment as a wall-clock timestamp). Only differences between two readings are meaningful.

For nanosecond precision there is also process.hrtime.bigint(), which returns a BigInt of nanoseconds from an arbitrary starting point. It is useful in tight benchmarks, but performance.now() is the one portable across browsers and Node.

console.time and its caveats

console.time('label') and console.timeEnd('label') are the quickest way to time something while debugging:

NODE
console.time('parse');
JSON.parse(bigText);
console.timeEnd('parse'); // prints something like: parse: 12.481ms

It is perfectly fine for a quick look, with these limits:

  • It prints instead of returning a value, so you cannot assert on it or send it to a metrics system.
  • The result is one sample, and a single sample is noisy (see the pitfalls below).
  • Labels are global. Starting the same label twice prints a warning, and forgetting timeEnd leaves the timer open.
  • The format changes with the duration (ms, s, min), which is awkward to parse.

Use console.time for exploring; use performance.now() or mark/measure when numbers must be stored or compared.

mark and measure: naming parts of a run

A mark is a named timestamp. A measure is the duration between two marks (or between explicit start and end times). Both are stored as performance entries that tools, dashboards and observers can read.

Node.js Marks and measures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that measure('total', 'load-start', 'render-end') spans a range that includes the other two. Marks make it easy to measure overlapping or nested stages without extra variables.

Entries pile up in memory until you clear them. A server that creates a mark for every request without clearing leaks memory slowly, so always clearMarks()/clearMeasures() (or by name) once you have read them, or use an observer that consumes them.

PerformanceObserver: collecting entries elsewhere

Instead of reading entries where you create them, register a PerformanceObserver once, and it receives entries as they are produced. That keeps measurement code out of business logic: your handlers only call mark/measure, and a single observer logs or exports them.

Node.js An observer that collects measures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Observers are notified asynchronously (in a later tick), which is why the example sleeps briefly before reading seen. Calling disconnect() stops the observer so the program can finish.

Besides 'mark' and 'measure', Node produces built-in entry types that you can observe the same way: 'function' (from timerify, next), 'gc' (every garbage collection), 'http' and 'http2' (server and client request timings), 'net' and 'dns' (connection and lookup timings), and 'resource' (for fetch). They are the raw material for monitoring tools.

timerify: time every call of a function

performance.timerify(fn) returns a wrapped function that behaves exactly like fn but records a 'function' entry for each call, including its duration. Observe the entries to collect timings for a function you do not want to edit.

Node.js timerify wraps a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

timerify also accepts a histogram option (from perf_hooks.createHistogram()) that accumulates the durations of all calls, so you can read the median, 99th percentile and maximum without storing every entry.

Is the event loop healthy?

In a Node server, the number that matters most is often not how long one function takes but whether the event loop is free. If any callback runs for 200 ms, every other request waits for it. Two tools measure that.

monitorEventLoopDelay: how late are we?

monitorEventLoopDelay() schedules a timer repeatedly and records how late each timer fires. In a calm loop the delay is a millisecond or so. A blocked loop shows up as large delays. It returns a histogram with min, max, mean, percentile(p) and exceeds values, in nanoseconds.

Node.js Detecting a blocked event loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The maximum jumped because one synchronous block delayed the sampling timer by almost its entire length. In production you would run this histogram permanently, export p99 and max to your metrics system every few seconds, call histogram.reset(), and alert when p99 crosses a threshold (say 100 ms).

eventLoopUtilization: how busy are we?

performance.eventLoopUtilization() reports how much of the time the loop spent active (running callbacks) versus idle (waiting for events). The utilization field is a ratio from 0 to 1. Called with a previous result, it returns the figures for the interval between the two calls.

Node.js Event loop utilization: busy versus idle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The await sleep(0) line matters: the loop only begins counting once the first turn of the program has finished, so top-level synchronous work before the first await is not part of the figures. A utilization consistently near 1 means the single thread is saturated: adding more traffic will increase latency sharply, and it is time to optimise the hot code, move work into worker threads, or add instances (Cluster, Scaling and Load Balancing). A load balancer can use it for load shedding: reply 503 quickly when utilization is above a limit instead of queueing work that will time out anyway.

Benchmarking without fooling yourself

A micro-benchmark is a small program that times one operation in a loop. They are easy to write and easy to get wrong:

  • Warm-up. The first runs are slow: V8 interprets the code, then optimises hot functions after thousands of calls. Run the code a few thousand times before you start timing.
  • Noise. Garbage collection, other processes and CPU frequency changes all vary. Take many samples and look at the median and percentiles, never one number.
  • Dead code elimination. If you throw away the result, the engine may skip the work. Use the result (sum it, store it).
  • Unrealistic input. A benchmark on ten items says nothing about a million. Use the data sizes you will really see, and test both small and large.
  • Measuring the wrong thing. Timing console.log or string building inside the loop measures those, not your function.
  • One run, one conclusion. A "30% faster" result inside the noise is not a result.

Often the most reliable comparison is not time at all, but counting the work: how many comparisons, allocations or database calls an approach needs. Counts are exact, repeatable and show why one approach scales better. This example counts the comparisons needed to find duplicates in a list in two ways.

Node.js Compare algorithms by counting operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When the list grows 40 times (100 to 4000 items), the nested-loop work grows roughly 1,600 times, while the Set version grows 40 times. That is the difference between O(n squared) and O(n), visible without a single timer. After the counts tell you which algorithm is better, use real timings on realistic data to see by how much and whether it matters.

Profiling: finding where the time goes

Measuring tells you how long; a profiler tells you where. These tools run on your own machine against a real program, so the commands are shown read-only:

Terminal
# Read-only: run on your computer

# 1. Built-in CPU profile: writes a .cpuprofile file you can open in Chrome DevTools
node --cpu-prof server.js

# 2. Debugger and DevTools profiler: open chrome://inspect in Chrome, click "inspect"
node --inspect server.js

# 3. V8's tick profiler, then a text summary
node --prof server.js
node --prof-process isolate-*.log > profile.txt

# 4. Heap profile for memory (see the V8 and memory lesson)
node --heap-prof server.js

A flame graph draws the profile: the horizontal axis is the share of time, the vertical axis the call stack, and wide boxes at the top are where the CPU actually spent its time. Third-party tools generate them with a single command:

Terminal
# Read-only: external tools, installed with npm
npx 0x server.js              # produces a flame graph in the browser
npx clinic doctor -- node server.js   # diagnoses event-loop, CPU, memory and I/O issues

A good workflow looks like this:

  1. Reproduce the slowness with realistic load (a load-testing tool such as autocannon, or a script with real data).
  2. Measure the baseline with a metric you will keep, such as p99 latency or event loop delay.
  3. Profile and find the widest boxes in the flame graph.
  4. Change one thing, then measure again with the same load.
  5. Keep the metric in production monitoring so that regressions are noticed.

More tuning advice is in Performance Tuning, and memory profiling in V8, Memory and Garbage Collection.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is performance.now() better than Date.now() for measuring durations?

    performance.now() never goes backwards even if the system clock changes, and it returns fractional milliseconds. Date.now() can jump and has millisecond resolution.
  2. 2. What does performance.measure('total', 'a', 'b') record?

    measure creates an entry of type 'measure' whose duration is the time between the two named marks.
  3. 3. What does a large maximum in monitorEventLoopDelay() tell you?

    The monitor records how late its own timer fires. A long synchronous task delays the timer by about its whole length.
  4. 4. Which is NOT a good micro-benchmarking practice?

    One sample is dominated by noise, JIT warm-up and garbage collection. Repeat and summarise.
  5. 5. Why does this lesson compare the two duplicate-finding functions by counting comparisons?

    Counts do not vary between machines or runs, and they show the growth rate, which is what decides how an algorithm behaves on large inputs.

Summary

  • Use performance.now() (monotonic, fractional milliseconds) for durations, not Date.now(). console.time is fine for quick debugging but prints instead of returning data.
  • mark and measure name sections of code; clear entries you no longer need so they do not accumulate.
  • PerformanceObserver collects measure, function, gc, http and other entries asynchronously, keeping measurement code out of your logic. timerify times every call of a function.
  • monitorEventLoopDelay() shows how late the loop is (a blocked loop gives a large max or p99); eventLoopUtilization() shows how busy it is.
  • Benchmark with warm-up, many samples, realistic data and used results, or compare by counting operations.
  • Profile with --cpu-prof, --inspect, 0x or clinic, change one thing at a time, and keep the metric in monitoring.

Next: JSON and Data Handling