Skip to main content

microbench 0.1.0 copy "microbench: ^0.1.0" to clipboard
microbench: ^0.1.0 copied to clipboard

Zero-dependency microbenchmark harness for Dart: robust timing, comparison tables in Markdown, HTML or text, JSON output, and README embedding.

microbench #

plugin version dart support likes test

A zero-dependency microbenchmark harness for Dart. Measure code reliably, compare implementations side by side, and publish the results as Markdown, HTML, plain text or JSON.

  • Robust timing: warmup, batches sized well above the timer resolution (which matters on the web), the median of many samples, and the spread between them.
  • Comparison tables: groups of competing implementations across columns such as input sizes, with the best result marked, proportional bars, and ratios against a baseline you choose.
  • Any metric: throughput (bits per second), operations per second, time per run, or units of your own such as chars/s.
  • Any output: Markdown, HTML (renders inside a README), aligned terminal text, or JSON. Tables stream as they are measured, so a long run shows progress.
  • Report tooling: write reports to files, embed them in a README between marker comments, and run benchmarks as AOT-compiled executables.
  • Runs everywhere: the core works on the VM, in AOT executables, and on the web (dart2js and dart2wasm). Supports Dart 2.19 and later.

Install #

Benchmarks are a development tool, so add it as a dev dependency:

dart pub add dev:microbench

Measure one benchmark #

Extend SyncBenchmark (or AsyncBenchmark) and return the result of the work from run(), so the compiler cannot optimize it away:

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)
}

For a quick one-off, wrap a closure instead:

final b = SyncBenchmark.from('sort', () => (List.of(data)..sort()), size: 4);
final m = await b.measure();
print('${m.rate} runs/s, ±${m.relativeDeviation * 100}%');

Use setup() and teardown() for work that should not be timed.

Compare in the terminal #

measureDiff measures a benchmark and others, then shows each one against the first:

await MyEncoder(size).measureDiff([OtherEncoder(size), ThirdEncoder(size)]);
// mine: <speed> [best]
// other: <speed> (4x slower)
// third: <speed> (2x slower)

Comparison tables #

runComparison builds a table of 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 the others are compared with.

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
);

Here is the text output of example/example.dart, which compares three ways to build a string:

Building a string
=================

Repeat one char  10 chars                                1000 chars
  + operator     8.56M chars/s                           8.21M chars/s
  StringBuffer   28.31M chars/s (3.31x faster)           50.76M chars/s (6.19x faster)
  * operator     500.17M chars/s [best] (58.43x faster)  676.22M chars/s [best] (82.41x faster)

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:

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
Comparison.toJson() JSON CI, tracking results over time

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).

Metrics #

Metric Shows size means
Metric.throughput (default) 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
);

BenchmarkOptions.standard is the default above; BenchmarkOptions.quick is about 0.3 s per benchmark, for smoke tests.

Each Measurement reports the median time per run (runtimeMicros), the fastest and slowest samples, the median absolute deviation (relativeDeviation), 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 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

Getting trustworthy numbers #

  • Publish numbers from AOT-compiled code (microbench:exe); dart run uses the JIT, whose results vary more.
  • Return the result of the work from run(), or the compiler may remove the work.
  • Keep input creation in the constructor or setup(), not in run().
  • Run on an idle machine, one benchmark process at a time, and say which machine in the report.
  • Check relativeDeviation: a 3% difference means little when the samples spread by 5%.

License #

BSD 3-Clause. See LICENSE.

1
likes
0
points
0
downloads

Publisher

verified publisherbitanon.dev

Weekly Downloads

Zero-dependency microbenchmark harness for Dart: robust timing, comparison tables in Markdown, HTML or text, JSON output, and README embedding.

Repository (GitHub)
View/report issues

Topics

#benchmark #performance #profiling #testing

Funding

Consider supporting this project:

paypal.me

License

unknown (license)

More

Packages that depend on microbench