Benchmark
- Dart course
- Advanced
- Lesson 73/83
- 5 min
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.
Practice 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').
Starter code
// import the benchmark_harness package
// define SortBenchmark (BenchmarkBase, super, run)
void main() {
// print benchmark info
}Sample 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');
}Expected output
Benchmark: ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a benchmark measure?
- Performance Correct answer
- Memory usage
- Correctness
- Security
Explanation: a benchmark measures performance (speed).
2 Extending BenchmarkBase
class SortBenchmark extends ____ { @override void run() { [3, 1, 2].sort(); } }
class SortBenchmark extends BenchmarkBase { @override void run() { [3, 1, 2].sort(); } }
Explanation: SortBenchmark extends BenchmarkBase.
3 Match the benchmark parts
| Term | Meaning |
|---|---|
BenchmarkBase |
Base class |
run |
Measured code |
warmup |
Warmup lap |
report |
Prints result |