benchmark function
void
benchmark(})
Defines a benchmark for the synchronous function run
. The benchmark
scores are emitted to stdout.
run
: the benchmarked function,setup
: exectued once before the benchmark,teardown
: executed once after the benchmark runs.emitStats
: Set tofalse
to emit score as provided by benchmark_harness.
Implementation
void benchmark(
String description,
void Function() run, {
void Function()? setup,
void Function()? teardown,
bool emitStats = true,
}) {
final group = Zone.current[#group] as Group?;
var groupDescription =
group == null ? '' : '${group.description.addSeparator(':')} ';
final instance = Benchmark(
description: groupDescription +
description.style(
ColorProfile.benchmark,
),
run: run,
setup: setup,
teardown: teardown,
);
final watch = Stopwatch()..start();
try {
if (run is Future<void> Function()) {
throw UnsupportedError('The callback "run" must not be marked async!');
}
} catch (error, stack) {
reportError(
error,
stack,
description: instance.description,
runtime: watch.elapsed,
errorMark: benchmarkError,
);
return;
}
runZonedGuarded(
() {
try {
if (emitStats) {
instance.reportStats();
} else {
instance.report();
}
addSuccessMark();
} catch (error, stack) {
reportError(
error,
stack,
description: instance.description,
runtime: watch.elapsed,
errorMark: benchmarkError,
);
}
},
((error, stack) {
// Safequard: Errors should be caught in the try block above.
reportError(
error,
stack,
description: instance.description,
runtime: watch.elapsed,
errorMark: benchmarkError,
);
}),
);
}