javascript / intermediate
Snippet
Precise Performance Benchmarking with BigInt
In Node.js, process.hrtime.bigint() provides a high-resolution real time in nanoseconds as a BigInt. It is monotonic, meaning it isn't affected by system clock drifts, making it perfect for micro-benchmarking.
snippet.js
1
2
3
4
5
6
7
8
9
const start = process.hrtime.bigint();// Complex operationfor(let i = 0; i < 1000000; i++) { Math.sqrt(i); }const end = process.hrtime.bigint();const durationNs = end - start;console.log(`Operation took ${durationNs} nanoseconds.`);console.log(`In milliseconds: ${Number(durationNs) / 1_000_000}ms`);
nodejs
Breakdown
1
process.hrtime.bigint()
Retrieves the current high-resolution time as a BigInt.
2
end - start
Performs BigInt subtraction to get the exact nanosecond difference.
3
Number(durationNs) / 1_000_000
Converts nanoseconds to milliseconds for human readability.