asyncBenchmark function

Future<void> asyncBenchmark(
  1. String description,
  2. Future<void> run(), {
  3. Future<void> setup()?,
  4. Future<void> teardown()?,
  5. bool emitStats = true,
  6. bool runInIsolate = true,
})

Defines an asynchronous benchmark.

  • 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.
  • runInIsolate: Set to true to run benchmarks in an isolate.

Implementation

Future<void> asyncBenchmark(
  String description,
  Future<void> Function() run, {
  Future<void> Function()? setup,
  Future<void> Function()? teardown,
  bool emitStats = true,
  bool runInIsolate = true,
}) async {
  final group = Zone.current[#group] as Group?;
  final groupDescription =
      group == null ? '' : '${group.description.addSeparator(':')} ';

  final instance = AsyncBenchmark(
    description: groupDescription +
        (hourGlass + description).style(
          ColorProfile.asyncBenchmark,
        ),
    run: run,
    setup: setup,
    teardown: teardown,
  );
  final watch = Stopwatch()..start();

  await runZonedGuarded(
    () async {
      try {
        switch ((emitStats, runInIsolate)) {
          case (true, true):

            /// Run method sample() in an isolate.
            final score = await Isolate.run(instance.score);
            (instance.emitter as ColorPrintEmitter).emitStats(
              description: instance.description,
              score: score,
            );
            addSuccessMark();
            break;
          case (true, false):
            await instance.reportStats();
            addSuccessMark();
            break;
          case (false, true):

            /// Run method measure() in an isolate.
            final watch = Stopwatch()..start();
            final score = await Isolate.run(instance.measure);
            final runtime = watch.elapsed.ssms.style(ColorProfile.dim);
            instance.emitter.emit(
              '$runtime ${instance.description}',
              score,
            );
            addSuccessMark();
            break;
          case (false, false):
            await 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,
      );
    }),
  );
}