benchmarks.dart 1.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'framework.dart';

/// A benchmark harness used to run a benchmark multiple times and report the
/// best result.
abstract class Benchmark {
  Benchmark(this.name);

  final String name;

  TaskResult bestResult;

  Future<Null> init() => new Future<Null>.value();

  Future<num> run();
  TaskResult get lastResult;

  @override
  String toString() => name;
}

/// Runs a [benchmark] [iterations] times and reports the best result.
///
/// Use [warmUpBenchmark] to discard cold performance results.
Future<num> runBenchmark(Benchmark benchmark, {
  int iterations: 1,
  bool warmUpBenchmark: false
}) async {
  await benchmark.init();

  List<num> allRuns = <num>[];

  num minValue;

  if (warmUpBenchmark)
    await benchmark.run();

  while (iterations > 0) {
    iterations--;

    print('');

    try {
      num result = await benchmark.run();
      allRuns.add(result);

      if (minValue == null || result < minValue) {
        benchmark.bestResult = benchmark.lastResult;
        minValue = result;
      }
    } catch (error) {
      print('benchmark failed with error: $error');
    }
  }

  return minValue;
}