javascript / intermediate
Snippet
Precise Performance Measurement
The perf_hooks module in Node.js provides a high-resolution timestamp API. Using performance.now() is much more accurate than Date.now() for measuring small execution time differences.
snippet.js
1
2
3
4
5
6
7
8
9
const { performance } = require('node:perf_hooks');const start = performance.now();// Perform intensive taskfor(let i = 0; i < 1e6; i++) { Math.sqrt(i); }const end = performance.now();console.log(`Task took ${end - start} milliseconds.`);
nodejs
Breakdown
1
require('node:perf_hooks')
Imports the performance hooks module for accessing high-resolution timers.
2
performance.now()
Returns a sub-millisecond resolution timestamp representing the current time.
3
end - start
Calculates the precise elapsed time in floating-point milliseconds.