0 Tage Serie
javascript / intermediate
Snippet

Präzises Performance-Benchmarking mit BigInt

In Node.js liefert process.hrtime.bigint() eine hochauflösende Echtzeit in Nanosekunden als BigInt. Sie ist monoton, d. h. sie wird nicht von Systemuhr-Drifts beeinflusst, was sie ideal für Mikro-Benchmarking macht.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const start = process.hrtime.bigint();
// Complex operation
for(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
Erklärung
1
process.hrtime.bigint()
Ruft die aktuelle hochauflösende Zeit als BigInt ab.
2
end - start
Führt eine BigInt-Subtraktion durch, um die exakte Differenz in Nanosekunden zu erhalten.
3
Number(durationNs) / 1_000_000
Konvertiert Nanosekunden in Millisekunden für die menschliche Lesbarkeit.