Last active
March 10, 2025 00:06
-
-
Save jdmarshall/2852b799091518bc64f71d6b27e73ee0 to your computer and use it in GitHub Desktop.
Clock jitter in hrtime.bigInt()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function bench() { | |
let samples = []; | |
let start = process.hrtime.bigint(); | |
for (let i = 0; i < 100_000_000; i++) { | |
let s = process.hrtime.bigint(); | |
let foo = JSON.parse('{ "a": 1, "b": 2, "c": 3, "d": 4 }'); | |
samples.push(process.hrtime.bigint() - s); | |
} | |
let total = process.hrtime.bigint() - start; | |
let sampledAverage = samples.reduce((acc, entry) => acc + entry, BigInt(0)); | |
console.log(total/BigInt(100_000_000), "average") | |
console.log(" vs"); | |
console.log(sampledAverage/BigInt(100_000_000), "sampled"); | |
} | |
function benchEmpty() { | |
let samples = []; | |
let start = process.hrtime.bigint(); | |
for (let i = 0; i < 100_000_000; i++) { | |
let s = process.hrtime.bigint(); | |
samples.push(process.hrtime.bigint() - s); | |
} | |
let total = process.hrtime.bigint() - start; | |
let sampledAverage = samples.reduce((acc, entry) => acc + entry, BigInt(0)); | |
console.log(sampledAverage/BigInt(100_000_000), "back-to-back hrtime()") | |
console.log(total/BigInt(100_000_000), "bookkeeping") | |
} | |
bench(); | |
console.log("benchEmpty():") | |
benchEmpty(); | |
bench(); | |
console.log("benchEmpty():") | |
benchEmpty(); | |
bench(); | |
console.log("benchEmpty():") | |
benchEmpty(); | |
/* | |
worst case from 3 runs. best run was 1-2ns, 1st run 2-5ns | |
338n average | |
vs | |
284n sampled | |
benchEmpty(): | |
7n back-to-back hrtime() | |
93n bookkeeping | |
334n average | |
vs | |
274n sampled | |
benchEmpty(): | |
12n back-to-back hrtime() | |
95n bookkeeping | |
340n average | |
vs | |
280n sampled | |
benchEmpty(): | |
10n back-to-back hrtime() | |
96n bookkeeping | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment