performance.now nodejs example
Here is an example of using the performance.now()
function in Node.js to measure performance:
const { performance } = require('perf_hooks');
const start = performance.now();
// Perform some time-consuming operation here
const end = performance.now();
const duration = end - start;
console.log(`The operation took ${duration} milliseconds`);
Explanation for each step:
Import the
performance
object from theperf_hooks
module. This object provides access to theperformance
interface, which includes thenow()
function for measuring performance.Declare a variable
start
to store the starting time of the operation. Assign it the value returned byperformance.now()
, which represents the current high-resolution timestamp in milliseconds.Perform the time-consuming operation you want to measure. This could be any code that takes a significant amount of time to execute.
Declare a variable
end
to store the ending time of the operation. Assign it the value returned byperformance.now()
after the time-consuming operation is completed.Calculate the duration of the operation by subtracting the starting time (
start
) from the ending time (end
). This gives the duration in milliseconds.Print the duration of the operation using
console.log()
, along with any additional information you want to include.
By using performance.now()
before and after the time-consuming operation, you can accurately measure the time it takes to execute the code block. This can be useful for optimizing performance and identifying bottlenecks in your Node.js applications.