0 Tage Serie
javascript / expert
Snippet

Benchmarking mit Nanosekunden-Präzision

Standard-Methoden wie Date.now() oder performance.now() können durch Zeit-Drift beeinflusst werden oder bieten nicht genug Auflösung für Micro-Benchmarks. process.hrtime.bigint() liefert einen monoton steigenden Nanosekunden-Timer für präzise Messungen.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const start = process.hrtime.bigint();
// Complex operation to measure
for(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
Erklärung
1
const start = process.hrtime.bigint();
Erfasst die aktuelle hochauflösende Zeit als BigInt, um Präzisionsverlust zu vermeiden.
2
const durationNs = end - start;
Führt eine BigInt-Subtraktion durch, um die exakt verstrichenen Nanosekunden zu erhalten.