microbench 0.2.0
microbench: ^0.2.0 copied to clipboard
Zero-dependency microbenchmark harness for Dart: robust timing, comparison tables in Markdown, HTML or text, JSON output, and README embedding.
example/example.dart
// Copyright (c) 2026, Sudipto Chandra
// All rights reserved. Check LICENSE file for details.
import 'package:microbench/microbench.dart';
/// Joins [count] short strings with `+`.
class ConcatBenchmark extends SyncBenchmark {
ConcatBenchmark(this.count) : super('+ operator', count);
final int count;
@override
Object? run() {
var s = '';
for (var i = 0; i < count; i++) {
s += 'x';
}
return s;
}
}
String buffer(int n) {
final sb = StringBuffer();
for (var i = 0; i < n; i++) {
sb.write('x');
}
return sb.toString();
}
// Try: dart run example/example.dart --thorough --verify --format=md
Future<void> main(List<String> args) => runMain(
args.isEmpty ? ['--quick', '--verify'] : args,
() async {
// 1. Closures side by side: one table, rows compared with the first.
await compare('Repeat one char, 1000 times', {
'+ operator': () => ConcatBenchmark(1000).run(),
'StringBuffer': () => buffer(1000),
'* operator': () => 'x' * 1000,
});
// 2. Every variant on every input: one column per case. With
// --verify, rows must return equal results for each case.
await matrix<int>(
'Building a string',
cases: [10, 1000],
label: (n) => '$n chars',
size: (n) => n,
metric: Metric.perSecond('chars'),
variants: {
'+ operator': (n) => ConcatBenchmark(n).run(),
'StringBuffer': buffer,
'* operator': (n) => 'x' * n,
},
);
// 3. Benchmark classes, for setup and teardown or reuse elsewhere.
await ConcatBenchmark(1000).measureRate(
options: BenchmarkSettings.current.options ?? BenchmarkOptions.quick,
metric: Metric.perSecond('chars'),
);
},
);