Dart
Benchmark
Learn performance measurement with benchmark.
Benchmark
A benchmark measures the speed of a piece of code. In Dart you use the package:benchmark_harness package. You write a class extending BenchmarkBase; the run method holds the code to measure and report prints the result.
Example: write class SortBenchmark extends BenchmarkBase and sort a list inside run. warmup runs a warmup lap; run does the actual measurement. The result is the time per run in microseconds; you see the performance impact of code changes.
The BenchmarkBase class
BenchmarkBase is the base class of the benchmark_harness package. You override three methods: warmup (warmup), run (measured code), teardown (cleanup). You give a name in the constructor with super('name').
Example: class SortBenchmark extends BenchmarkBase { SortBenchmark() : super('sort'); @override void run() { [3, 1, 2].sort(); } }. The call SortBenchmark().report(); runs the measurement and prints the result. This is used to see the performance impact of code changes. The warmup lap lets the JIT compiler enter hot code, so the actual measurement is more stable.
Exercise The SortBenchmark class
Add import 'package:benchmark_harness/benchmark_harness.dart';. Define the SortBenchmark class: extend BenchmarkBase, call super('sort') in the constructor, and sort [3, 1, 2] in run. In main add print('Benchmark: ready').
Show example solution
import 'package:benchmark_harness/benchmark_harness.dart';
class SortBenchmark extends BenchmarkBase {
SortBenchmark() : super('sort');
@override
void run() {
[3, 1, 2].sort();
}
}
void main() {
print('Benchmark: ready');
}
Test yourself
-
What does a benchmark measure?
- Performance
- Memory usage
- Correctness
- Security
Show answer
Performance — a benchmark measures performance (speed).
-
Extending BenchmarkBase
class SortBenchmark extends ____ { @override void run() { [3, 1, 2].sort(); } }
Show answer
class SortBenchmark extends BenchmarkBase { @override void run() { [3, 1, 2].sort(); } }
-
Match the benchmark parts
- BenchmarkBase
- Base class
- run
- Measured code
- warmup
- Warmup lap
- report
- Prints result
Next lesson: Stopwatch