Node.js perf_hooks Module
Node.js'sperf_hooksThe module is a performance monitoring tool that allows developers to measure and monitor the execution performance of code in applications. This module provides high-precision performance timing functionality to help you identify performance bottlenecks in your code.
perf_hooksIt is the abbreviation for "Performance Hooks". Based on the Web Performance API standard, it provides performance measurement capabilities for Node.js applications.
Core Features of perf_hooks
1. Performance Timing
perf_hooksThe module can precisely measure the execution time of code blocks, with precision reaching the nanosecond level.
2. Resource Monitoring
It can monitor the resource usage of Node.js processes, including CPU time, memory usage, etc.
3. Performance Observation
It provides an observer pattern to continuously monitor specific types of performance metrics.
How to Use perf_hooks
First, you need to importperf_hooksthe module:
Basic Performance Measurement Example
Example
// Record start time
const startTime = performance.now();
// Perform some operations
for (let i = 0; i < 1000000; i++) {
Math.sqrt(i);
}
// Record end time
const endTime = performance.now();
console.log(`This code execution took: ${endTime - startTime}milliseconds`);
Using PerformanceObserver
PerformanceObserverYou can listen to performance entries and respond:
Example
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration);
performance.clearMarks();
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('A');
doSomeLongOperation();
performance.mark('B');
performance.measure('A to B', 'A', 'B');
Main APIs of perf_hooks
1. performance.now()
Returns the current high-resolution timestamp, in milliseconds.
2. performance.mark(name)
Creates a named timestamp marker in the performance timeline.
3. performance.measure(name, startMark, endMark)
Measures the time interval between two markers.
4. PerformanceObserver
A class used to observe performance measurement events.
5. performance.timerify(fn)
Wraps a function so that its execution time can be measured.
Practical Application Scenarios
1. API Response Time Monitoring
Example
app.use((req, res, next) => {
const start = performance.now();
res.on('finish', () => {
console.log(`${req.method} ${req.url} ${performance.now() - start}ms`);
});
next();
});
2. Function Performance Analysis
Example
const obs = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
console.log(`Function ${entry.name} took ${entry.duration}ms`);
});
});
obs.observe({ entryTypes: ['function'] });
function slowFunction() {
// Some time-consuming operations
}
// Use timerify to wrap a function
const timedSlowFunction = performance.timerify(slowFunction);
timedSlowFunction();
Precautions
perf_hooksPerformance measurement itself incurs some performance overhead and should be used with caution in production environments.Time measurement results are affected by system load and other factors, so multiple measurements should be taken and averaged.
In different versions of Node.js,
perf_hooksthe implementation may differ, and version compatibility should be considered.For very short operations (nanosecond level), measurement results may not be accurate enough.
Summary
Node.js'sperf_hooksThe module provides developers with powerful performance monitoring capabilities, helping to identify and optimize performance bottlenecks in code. Through reasonable useperformanceandPerformanceObserver, developers can obtain precise performance data, thereby making more targeted optimization decisions.
In actual projects, it is recommended to integrate performance monitoring with the logging system and establish long-term performance baselines to promptly detect performance regression issues.
Other Extensions
Node.js Built-in Modules