Skip to content

Commit

Permalink
Benchmark edge cases better.
Browse files Browse the repository at this point in the history
  • Loading branch information
lgarron committed Jun 6, 2024
1 parent 44ad379 commit d489bb4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/benchmark/benchmark.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
const originalGetRandomValues = globalThis.crypto.getRandomValues.bind(
globalThis.crypto,
);

let counter = 0;

globalThis.crypto.getRandomValues = (array) => {
counter++;
return originalGetRandomValues(array);
};

import { randomUIntBelow } from "../random-uint-below";

const DEFAULT_NUM_RUNS = 1_000_000;
const DEFAULT_MAX = 1337;

export function benchmark(options?: { numRuns?: number; max?: number }) {
counter = 0;
const start = performance.now();
let total = 0;
const numRuns = options?.numRuns ?? DEFAULT_NUM_RUNS;
Expand All @@ -14,7 +26,7 @@ export function benchmark(options?: { numRuns?: number; max?: number }) {
total += randomUIntBelow(max);
}
console.log(
`Finished ${numRuns} runs for max ${max} in: ${Math.floor((performance.now() - start) * 1000) / 1000}ms`,
`Finished ${numRuns} runs for max ${max} in: ${Math.floor((performance.now() - start) * 1000) / 1000}ms (${counter} calls)`,
);
console.log(
`Mean of generated values (should be ≈${(max - 1) / 2}): ${total / numRuns}`,
Expand Down
3 changes: 2 additions & 1 deletion src/benchmark/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { benchmark } from "./benchmark";

benchmark();
benchmark({ numRuns: 1_000_000, max: 2 ** 52 });
benchmark({ numRuns: 1_000_000, max: 7 });
benchmark({ numRuns: 1_000_000, max: 2 ** 52 });
benchmark({ numRuns: 1_000_000, max: 2 ** 52 + 1 });
benchmark({ numRuns: 1_000_000, max: 3 * 2 ** 51 });
10 changes: 10 additions & 0 deletions src/random-uint-below/randomUIntBelow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,18 @@ const MAX_JS_PRECISE_INT = 2 ** 53;
const UPPER_HALF_MULTIPLIER = 2097152; // 2^21.
const LOWER_HALF_RIGHT_SHIFT_BITS = 11;

let counter = 0;

export function resetCounter() {
counter = 0;
}
export function getCounter(): number {
return counter;
}

const arr = new Uint32Array(2);
function random53BitNumber(): number {
counter++;
// Construct a random 53-bit value from a 32-bit upper half and a 21-bit lower half.
// Note that in theory it *could* be faster to construct only a 32-bit number when needed, but the impact on performance is negligible.
globalThis.crypto.getRandomValues(arr);
Expand Down

0 comments on commit d489bb4

Please sign in to comment.