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:

  1. Import the performance object from the perf_hooks module. This object provides access to the performance interface, which includes the now() function for measuring performance.

  2. Declare a variable start to store the starting time of the operation. Assign it the value returned by performance.now(), which represents the current high-resolution timestamp in milliseconds.

  3. Perform the time-consuming operation you want to measure. This could be any code that takes a significant amount of time to execute.

  4. Declare a variable end to store the ending time of the operation. Assign it the value returned by performance.now() after the time-consuming operation is completed.

  5. Calculate the duration of the operation by subtracting the starting time (start) from the ending time (end). This gives the duration in milliseconds.

  6. 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.