Files
test-repo/benchmarks/utilities.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

63 lines
1.2 KiB
JavaScript
Raw Normal View History

import { Bench } from "tinybench";
/**
@import {BenchOptions} from "tinybench";
@typedef {
| {
name: string,
implementation: () => any
}[]
| Record<string, () => any>
} Implementations
*/
/**
@param {
| string
| {
name: string,
assert?: (result: any) => void,
} & BenchOptions
} options
@param {Implementations} implementations
*/
async function runBenchmark(options, implementations) {
if (typeof options === "string") {
options = { name: options };
}
const { assert, ...benchOptions } = options;
2026-01-02 13:41:28 +08:00
const bench = new Bench({ throws: true, ...benchOptions });
let error;
for (const { name, implementation } of Array.isArray(implementations)
? implementations
: Object.entries(implementations).map(([name, implementation]) => ({
name,
implementation,
}))) {
bench.add(name, () => {
try {
const result = implementation();
assert?.(result);
} catch (assertionError) {
error ??= Object.assign(assertionError, {
case: `${benchOptions.name} >> ${name}`,
});
}
});
}
await bench.run();
console.log(bench.name);
console.table(bench.table());
if (error) {
throw error;
}
}
export { runBenchmark };