microbench 0.3.1
microbench: ^0.3.1 copied to clipboard
Zero-dependency microbenchmark harness for Dart: robust timing, comparison tables in Markdown, HTML or text, JSON output, and README embedding.
microbench #
A zero-dependency microbenchmark harness for Dart. Compare implementations side by side, know whether a difference is real, catch regressions in CI, and publish the results as Markdown, HTML, plain text or JSON.
- Written like tests:
benchmark()andgroup()read likepackage:test;comparetakes a map of closures, andmatrixruns every variant on every input. - Numbers you can trust: warmup, batches sized well above the timer
resolution, rounds that alternate between rows so drift hits all of them
equally, a significance test that marks noise with
≈, warnings when the work was likely optimized away, and--verifyto check that every variant returns the same result. - A command line for free:
--quick,--filter,--format,--out,--saveand--baselinework for every benchmark program, with no argument handling of your own. - Regression checks: save results as JSON, compare a later run with them, and fail CI when something got slower.
- Every runtime:
dart run microbench --target=jit,aot,js,wasmcompiles and runs your benchmarks on each; results record which one they came from. The core runs on the VM, AOT and the web, on Dart 2.19 and later.
Install #
Benchmarks are a development tool, so add it as a dev dependency:
dart pub add dev:microbench
Quick start #
New to benchmarking? Your first benchmark
walks through this step by step. Put this in
benchmark/string_benchmark.dart:
import 'package:microbench/suite.dart';
void main() {
group('Repeat one char, 1000 times', () {
benchmark('StringBuffer', () {
final sb = StringBuffer();
for (var i = 0; i < 1000; i++) {
sb.write('x');
}
return sb.toString();
});
benchmark('* operator', () => 'x' * 1000);
});
}
Return the result of the work from each benchmark, so the compiler cannot remove the work. Then run it:
dart run microbench benchmark/string_benchmark.dart -- --quick
This compiles the file to native code and runs it; options go after --.
dart run microbench -- --quick runs every *_benchmark.dart under
benchmark/.
The first benchmark of a group is the baseline the others are compared with. Here is example/example.dart on one machine:
Repeat one char, 1000 times Rate
+ operator 8.57K ops/s
StringBuffer 57.79K ops/s (6.74x faster)
* operator 684.09K ops/s [best] (79.82x faster)
benchmark also takes size (units processed per run, to show
throughput), and setup and teardown callbacks that run outside the
timed part. Nested groups join their names.
One call: compare #
compare builds the same table from a map of closures, right away, and
returns it:
String buffer(int n) {
final sb = StringBuffer();
for (var i = 0; i < n; i++) {
sb.write('x');
}
return sb.toString();
}
final table = await compare('Repeat one char, 1000 times', {
'StringBuffer': () => buffer(1000),
'* operator': () => 'x' * 1000,
});
Many inputs: matrix #
matrix runs every variant on every case and makes one column per case.
Give a size to measure throughput:
await matrix<int>(
'Building a string',
cases: [10, 1000],
label: (n) => '$n chars',
size: (n) => n,
metric: Metric.perSecond('chars'),
variants: {
'StringBuffer': buffer,
'* operator': (n) => 'x' * n,
},
);
Building a string 10 chars 1000 chars
+ operator 11.72M chars/s 8.58M chars/s
StringBuffer 40.79M chars/s (3.48x faster) 57.28M chars/s (6.67x faster)
* operator 429.89M chars/s [best] (36.69x faster) 689.49M chars/s [best] (80.32x faster)
Without size, the cases' toString labels the columns and the metric is
operations per second.
Command-line options #
Every benchmark, compare, matrix and runComparison picks up these
options. Pass them after -- to dart run microbench. To pass them to
dart run <file> directly, hand main's arguments over with
runSuite(args, body) (or its twin runMain, from
package:microbench/microbench.dart): Dart gives a program's arguments only
to main.
| Option | Effect |
|---|---|
--quick / --thorough |
short smoke runs / long, 8-round runs |
--filter=REGEX |
only rows whose title / group / row matches |
--format=FORMAT |
text, markdown, html or json |
--out=FILE |
also write the tables to FILE; the extension picks the format |
--verify |
fail if the rows of a group return different results |
--save=FILE |
save every result as JSON lines |
--baseline=FILE |
compare with saved results; exit code 1 on a regression |
--threshold=PCT |
smallest change --baseline reports (default 5) |
Arguments a call passes itself win over these. Under the hood,
dart run microbench passes the options in the MICROBENCH_ARGS
environment variable (a JSON list, or options separated by spaces), which a
plain main reads; you can set it yourself too.
Trusting the numbers #
Alternating rounds. The rows of a column are measured in rounds,
in A B B A order, rather than one after another. CPU frequency changes and
background load then hit every row about equally. Set the number of rounds
with BenchmarkOptions(rounds: ...).
Significance. Every sample is kept. A cell whose difference from the
baseline fails a Mann-Whitney U test (p ≥ 0.05) gets ≈ in Markdown and
HTML, or (≈ same) in text: the difference is probably noise. Change the
level with runComparison(alpha: ...), or call mannWhitneyP yourself.
Each Measurement also has meanMicros, stdDevMicros and cv.
Warnings. Tables list suspicious results below them: a run under 1 ns
(the work was likely optimized away) and a time that does not grow with the
input size. Turn them off with showWarnings: false on a renderer.
Verification. With --verify, or verify: true on a call, the first
result of every row is compared with the baseline row's (lists, maps and
sets by content), and a mismatch throws OutputMismatchError before any
timing.
More in Getting trustworthy numbers.
Catching regressions #
Save a run, then compare later runs with it:
dart run benchmark/main.dart --save=baseline.jsonl
# ... change the code ...
dart run benchmark/main.dart --baseline=baseline.jsonl
The second run prints each benchmark's change and exits with code 1 if any got slower by more than the threshold and the difference is significant. To compare two saved files:
dart run microbench diff before.jsonl after.jsonl --threshold=10
In code, BenchmarkDiff(before, after) does the same with Comparisons,
and parseComparisons reads saved files.
Machines differ, so compare runs from the same machine only.
Every runtime #
# Every benchmark/*_benchmark.dart, compiled to native code (the default).
dart run microbench
# Chosen files and runtimes; arguments after -- go to every program.
dart run microbench --target=jit,aot,js,wasm benchmark/sort_benchmark.dart -- --quick
js and wasm run on Node.js (dart2wasm needs Node.js 22 or later).
Programs compiled for the web get no command line, so run passes the
arguments through a define that runMain reads. Every saved table records
its environment: the runtime (detectRuntime()), the Dart version and the
time.
Benchmark classes #
For more control, extend SyncBenchmark (or AsyncBenchmark):
import 'dart:convert';
import 'package:microbench/microbench.dart';
class Utf8Encode extends SyncBenchmark {
Utf8Encode(this.text) : super('dart:convert', text.length);
final String text;
@override
Object? run() => utf8.encode(text);
}
Future<void> main() async {
await Utf8Encode('a' * 1024).measureRate();
// prints: name: throughput | time/run ±spread (runs, samples)
}
Use setup() and teardown() for work that should not be timed.
SyncBenchmark.from wraps a closure. measureDiff measures a benchmark
and others, then shows each against the first:
await MyEncoder(size).measureDiff([OtherEncoder(size), ThirdEncoder(size)]);
// mine: <speed> [best]
// other: <speed> (4x slower)
// third: <speed> (1.02x slower) (≈ same): probably noise
Moving from benchmark_harness? See the
migration guide.
Comparison tables #
compare and matrix build on runComparison, which takes groups (rows
that compete with each other) and columns (inputs). For each group, a
builder returns that column's benchmarks; the first is the baseline.
const sizes = [1 << 20, 1 << 10, 32];
final table = await runComparison(
title: 'Encoding',
columns: [for (final s in sizes) formatSize(s)],
groupHeader: 'Codec',
rowHeader: 'Library',
groups: {
'Base64': (c) => [MyBase64(sizes[c]), DartBase64(sizes[c])],
'Hex': (c) => [
MyHex(sizes[c]),
// keep the row, but leave this cell empty
sizes[c] > 1024 ? const SkippedBenchmark('slow_hex') : SlowHex(sizes[c]),
],
},
out: stdout, // from dart:io; stream as it runs
renderer: const TextTableRenderer(), // or Markdown/Html/Json
);
Builders run only when their group is measured, so large inputs can be
freed between groups. The result is a Comparison you can render again in
any format, or serialize and read back with Comparison.fromJson:
print(const MarkdownTableRenderer().render(table));
print(const HtmlTableRenderer().render(table));
print(jsonEncode(table.toJson()));
Renderers #
| Renderer | Output | Best for |
|---|---|---|
MarkdownTableRenderer |
GitHub-flavored Markdown table | docs, PR comments |
HtmlTableRenderer |
<table> with group names spanning rows |
README files |
TextTableRenderer |
aligned plain text | terminals, logs |
JsonTableRenderer |
one JSON line per table | CI, --baseline |
Markdown and HTML cells show a bar, the value, a mark on the best cell, and
a ratio against the baseline. Change any of it with CellStyle:
const HtmlTableRenderer(
style: CellStyle(barWidth: 0, ratios: false), // numbers only
headingLevel: 2, // "## Title"
);
Write your own format by extending TableRenderer; Comparison.cell()
gives each cell's ranking (best, ratio, bar fraction, significance).
Metrics #
| Metric | Shows | size means |
|---|---|---|
Metric.throughput |
4.2 Gbps |
bytes per run |
Metric.rate |
1.2M ops/s |
unused |
Metric.runtime |
384.1 ns |
unused |
Metric.perSecond('chars') |
5.3M chars/s |
chars per run |
A custom Metric needs a name, a higher-is-better score, and a format.
Timing options #
Every measuring call takes BenchmarkOptions:
const options = BenchmarkOptions(
warmup: Duration(milliseconds: 100), // minimum warmup
duration: Duration(seconds: 2), // minimum measuring time
batchTarget: Duration(milliseconds: 25),// target time of one batch
minBatch: 10, // fewest runs per batch
rounds: 4, // alternating rounds per column
);
BenchmarkOptions.standard is the default above. BenchmarkOptions.quick
takes about 0.3 s per benchmark, for smoke tests, and
BenchmarkOptions.thorough about 5 s in 8 rounds, for numbers you publish.
Each Measurement reports the median time per run (runtimeMicros), the
fastest and slowest samples, the median absolute deviation
(relativeDeviation), the samples themselves, and derived rate and
speed.
Reports and tooling (VM only) #
package:microbench/io.dart adds helpers that need dart:io:
import 'package:microbench/io.dart';
Future<void> main() async {
final report = ReportFile('BENCHMARK.md'); // also echoes to stdout
report.writeln('## Benchmarks\n');
await runComparison(
columns: ['1KB'],
groups: {/* ... */},
out: report,
renderer: const HtmlTableRenderer(),
);
report.writeln('> ${environmentSummary()}');
report.close();
}
Two more executables come with the package:
# Compile a benchmark to a native executable and run it.
dart run microbench:exe benchmark/main.dart BENCHMARK.md
# Copy BENCHMARK.md into README.md between these two lines:
# <!-- file: BENCHMARK.md -->
# <!-- end BENCHMARK.md -->
dart run microbench:embed
dart run microbench:embed --source=PERF.md --target=doc/index.md
Examples #
example/example.dart is the simplest. Each of the others shows one way to use microbench:
| Example | Shows |
|---|---|
| suite_example.dart | benchmark()/group() in a plain main: nested groups, untimed setup, throughput |
| compare_example.dart | compare with sync and async closures, verify, using the returned table |
| matrix_example.dart | matrix over input sizes, with a custom unit (items/s) |
| class_example.dart | SyncBenchmark/AsyncBenchmark classes, raw Measurement statistics, measureDiff |
| table_example.dart | runComparison with groups and columns, skipped cells, a custom Metric, every renderer |
| custom_renderer_example.dart | a TableRenderer of your own (CSV) |
| settings_example.dart | BenchmarkSettings to configure a block from code and collect its tables |
| regression_example.dart | saving results as JSON and BenchmarkDiff against them |
| report_example.dart | ReportFile, environmentSummary and embedFile (VM only) |
Guides #
New to benchmarking? Start here:
- Your first benchmark: from install to a result in five minutes
- Reading the results: every column, mark and warning explained
- Recipes: input sizes, async code, reports, CI checks
Going further:
- Getting trustworthy numbers
- Migrating from benchmark_harness
License #
BSD 3-Clause. See LICENSE.