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 36f8464
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 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
9 changes: 7 additions & 2 deletions src/benchmark/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
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: 3 * 2 ** 51 });
benchmark({ numRuns: 100_000, max: 2 ** 52 - 1 });
benchmark({ numRuns: 100_000, max: 2 ** 52 });
benchmark({ numRuns: 100_000, max: 2 ** 52 + 1 });
benchmark({ numRuns: 100_000, max: 3 * 2 ** 51 });
benchmark({ numRuns: 100_000, max: 2 ** 53 - 1 });
benchmark({ numRuns: 100_000, max: (2 ** 53 / 16) * 15 });
benchmark({ numRuns: 100_000, max: 2 ** 53 });
2 changes: 1 addition & 1 deletion src/random-uint-below/randomUIntBelow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function randomUIntBelow(max: number): number {
val = random53BitNumber();
block = Math.floor(val / max);
blockMax = block * max;
if (blockMax < MAX_JS_PRECISE_INT - max) {
if (blockMax <= MAX_JS_PRECISE_INT - max) {
return val - blockMax;
}
}
Expand Down

0 comments on commit 36f8464

Please sign in to comment.