javascript / expert
Snippet
Nanosecond Precision Benchmarking
Standard Date.now() or performance.now() can be susceptible to clock drift or insufficient resolution for micro-benchmarks. process.hrtime.bigint() provides a monotonically increasing nanosecond timer ideal for measuring hot code paths.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const start = process.hrtime.bigint();// Complex operation to measurefor(let i = 0; i < 1e6; i++) { Math.sqrt(i); }const end = process.hrtime.bigint();const durationNs = end - start;const durationMs = Number(durationNs) / 1_000_000;console.log(`Execution took ${durationNs}ns (${durationMs.toFixed(4)}ms)`);
nodejs
Breakdown
1
const start = process.hrtime.bigint();
Captures the current high-resolution time as a BigInt to prevent precision loss.
2
const durationNs = end - start;
Performs BigInt subtraction to get the exact nanoseconds elapsed.