benchmark function

void benchmark(
  1. String description,
  2. void run(), {
  3. void setup()?,
  4. void teardown()?,
  5. bool emitStats = true,
})

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 to false 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,
      );
    }),
  );
}