Measure Node.js performance with perf_hooks Module!
Node.js perf_hooks is a built-in module that provides performance measurement and monitoring capabilities for Node.js applications. It allows you to analyze the performance of your code by measuring the execution time of specific sections or functions.
The perf_hooks module provides several classes and methods for performance measurement, including:
Here's an example that demonstrates the usage of perf_hooks to measure the execution time of a function:
领英推荐
const { performance, PerformanceObserver } = require('perf_hooks')
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Create a PerformanceObserver to collect performance entries
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
console.log(entry);
});
});
observer.observe({ entryTypes: ["measure"], buffer: true })
// Measure the performance of the fibonacci function
performance.mark('start');
fibonacci(40);
performance.mark('end');
performance.measure('fibonacci', 'start', 'end');
In the example above, we first import the necessary classes and methods from the perf_hooks module. Then, we define a recursive fibonacci function to calculate the Fibonacci sequence. We create a PerformanceObserver instance and subscribe to the function entry type.
Next, we use performance.mark() to create marks before and after calling the fibonacci function. Finally, we use performance.measure() to measure the duration between the marks and collect the performance entry.
When you run this code, it will output the name and duration of the performance entry. In this case, it will display the duration of the fibonacci function execution.
PerformanceMeasure {
? name: 'fibonacci',
? entryType: 'measure',
? startTime: 60.554721999913454,
? duration: 2626.6919049993157,
? detail: null
}
Go, Node! ????