tezvyn:

Node.js perf_hooks: A High-Precision Stopwatch for Your App

AI-drafted, machine-checkedSource: nodejs.orgintermediate

The `perf_hooks` module is a high-precision stopwatch for your Node.js code, offering nanosecond accuracy. Use it to benchmark async operations or HTTP request durations.

WHY IT EXISTS Node.js needed a standardized, high-resolution way to measure performance inside an application. Simple timing with Date.now() isn't accurate enough for diagnosing small bottlenecks and can be affected by system time changes, which can even go backward. perf_hooks provides a stable, monotonic clock that only moves forward, ensuring reliable measurements.

THE MENTAL MODEL Think of perf_hooks as a set of stopwatches and lap timers built directly into Node.js. You can place "marks" (like pressing the lap button) at different points in your code and then "measure" the duration between any two marks. This gives you precise timings for specific code paths, independent of the system's wall-clock time.

HOW IT WORKS The core functions are performance.mark('start-A') and performance.mark('end-A'). These create named timestamps in a performance timeline. You then call performance.measure('A-duration', 'start-A', 'end-A') to create a new entry that calculates the duration between the marks. For continuous monitoring, you can use a PerformanceObserver to subscribe to performance events (like measures, garbage collection, or HTTP timings) as they happen. The module also includes timerify to automatically wrap and measure a function's execution time.

WHEN TO USE IT Use perf_hooks when you need to answer specific performance questions. For example: "How long does this database query take under load?", "What's the P99 latency of this API endpoint?", or "How much time is spent loading modules at startup?". It's the right tool for fine-grained, application-level profiling and a building block for custom APM (Application Performance Monitoring) tools.

WHEN NOT TO USE IT Avoid perf_hooks for measuring wall-clock time or for tasks that don't require high precision. For simple "how long did this whole script run" checks, console.time() might be sufficient. It is not a full-scale, out-of-the-box APM solution but rather a low-level API to build such tooling.

ONE CANONICAL EXAMPLE To measure the time it takes to load a dependency, you can mark the time before and after the require call. First, const { performance } = require('perf_hooks');. Then, in your code: performance.mark('start-load'); const myModule = require('heavy-dependency'); performance.mark('end-load'); performance.measure('Module Load: heavy-dependency', 'start-load', 'end-load');. You can then retrieve this measurement with performance.getEntriesByName('Module Load: heavy-dependency')[0] to see its duration in milliseconds.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.