Skip to content

Commit

Permalink
refactor: factor out benchmarks execution into an helper
Browse files Browse the repository at this point in the history
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
  • Loading branch information
jerome-benoit committed May 17, 2024
1 parent fa9a60e commit 25dbc11
Showing 1 changed file with 29 additions and 31 deletions.
60 changes: 29 additions & 31 deletions src/benchmark.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,25 +193,32 @@ export function clear() {
benchmarks.length = 0;
}

const runBenchmark = async (benchmark, log, opts = {}) => {
try {
benchmark.stats = await measure(
benchmark.fn,
benchmark.before,
benchmark.after,
{
async: benchmark.async,
samples: benchmark.samples,
time: benchmark.time,
warmup: benchmark.warmup,
},
);
if (!opts.json) log(table.benchmark(benchmark.name, benchmark.stats, opts));
} catch (err) {
benchmark.error = err;
if (!opts.json)
log(table.benchmarkError(benchmark.name, benchmark.error, opts));
const executeBenchmarks = async (benchmarks, log, opts = {}) => {
let once = false;
for (const benchmark of benchmarks) {
once = true;
overrideBenchmarkDefaults(benchmark, opts);
try {
benchmark.stats = await measure(
benchmark.fn,
benchmark.before,
benchmark.after,
{
async: benchmark.async,
samples: benchmark.samples,
time: benchmark.time,
warmup: benchmark.warmup,
},
);
if (!opts.json)
log(table.benchmark(benchmark.name, benchmark.stats, opts));
} catch (err) {
benchmark.error = err;
if (!opts.json)
log(table.benchmarkError(benchmark.name, benchmark.error, opts));
}
}
return once;
};

/**
Expand Down Expand Up @@ -302,12 +309,7 @@ export async function run(opts = {}) {
const noGroupBenchmarks = benchmarks.filter(
benchmark => benchmark.group == null,
);
let first = false;
for (const benchmark of noGroupBenchmarks) {
overrideBenchmarkDefaults(benchmark, opts);
first = true;
await runBenchmark(benchmark, log, opts);
}
let once = await executeBenchmarks(noGroupBenchmarks, log, opts);

if (!opts.json && noGroupBenchmarks.length > 0) {
log('');
Expand All @@ -316,9 +318,9 @@ export async function run(opts = {}) {

for (const [group, groupOpts] of groups) {
if (!opts.json) {
if (first) log('');
if (once) log('');
if (!group.startsWith(tatamiNgGroup)) log(`• ${group}`);
if (first || !group.startsWith(tatamiNgGroup))
if (once || !group.startsWith(tatamiNgGroup))
log(clr.gray(opts.colors, table.br(opts)));
}

Expand All @@ -329,11 +331,7 @@ export async function run(opts = {}) {
const groupBenchmarks = benchmarks.filter(
benchmark => benchmark.group === group,
);
for (const benchmark of groupBenchmarks) {
overrideBenchmarkDefaults(benchmark, opts);
first = true;
await runBenchmark(benchmark, log, opts);
}
once = await executeBenchmarks(groupBenchmarks, log, opts);

AsyncFunction === groupOpts.after.constructor
? await groupOpts.after()
Expand Down

0 comments on commit 25dbc11

Please sign in to comment.