Skip to content

Migrating from benchmark_harness

Port one benchmark first. Keep the input, setup, and timed operation the same, then establish a fresh baseline with microbench before moving the rest of the suite.

benchmark_harness microbench
class X extends BenchmarkBase class X extends SyncBenchmark
class X extends AsyncBenchmarkBase class X extends AsyncBenchmark
X() : super('name') X() : super('name'), or super('name', bytesPerRun) for throughput
void run() Object? run(): return the result
void setup() / void teardown() the same, still untimed
X().report() await X().measureRate()
X().measure() (microseconds) (await X().measure()).runtimeMicros
ScoreEmitter a TableRenderer, or log: on measureRate

Before:

import 'package:benchmark_harness/benchmark_harness.dart';
class SortBenchmark extends BenchmarkBase {
SortBenchmark() : super('sort');
late List<int> data;
@override
void setup() => data = List.generate(1000, (i) => (i * 7919) % 1000);
@override
void run() => List.of(data)..sort();
}
void main() => SortBenchmark().report();

After:

import 'package:microbench/microbench.dart';
class SortBenchmark extends SyncBenchmark {
SortBenchmark() : super('sort');
late List<int> data;
@override
void setup() => data = List.generate(1000, (i) => (i * 7919) % 1000);
@override
Object? run() => List.of(data)..sort();
}
Future<void> main() => SortBenchmark().measureRate(metric: Metric.runtime);

Returning the result matters: microbench keeps it alive, so the compiler cannot decide the work is unused and remove it.

Most benchmarks need no class at all. Declare them like tests:

import 'package:microbench/suite.dart';
Future<void> main(List<String> args) => runSuite(args, () {
final data = List.generate(1000, (i) => (i * 7919) % 1000);
group('sort 1000 ints', () {
benchmark('List.sort', () => List.of(data)..sort());
benchmark('sorted copy', () => ([...data]..sort()));
});
});

setup and teardown become named arguments of benchmark. Or measure a map of closures right away with compare:

await compare('sort 1000 ints', {
'List.sort': () => List.of(data)..sort(),
'sorted copy': () => ([...data]..sort()),
});

Do not compare old and new numbers directly:

  • benchmark_harness times exercise(), which by default calls run() ten times. microbench reports the time of one run().
  • microbench reports the low end of many samples, not a mean over the whole timing window, so a few slow outliers move it less.

Measure the old and new code again with microbench, side by side, instead.

  • Several implementations in one table, compared with a baseline row and marked ≈ when the difference is noise.
  • --verify, to check that every implementation returns the same result.
  • --save and --baseline, to fail CI on a regression.
  • dart run microbench --target=jit,aot,js,wasm, to run on every runtime.

All guides · Designing comparisons