| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 library code_transformers.src.async_benchmark_base; |
| 5 |
| 6 import 'dart:async'; |
| 7 |
| 8 /// An adaptation of [BenchmarkBase] from the `benchmark_harness` package that |
| 9 /// works for async benchmarks. |
| 10 /// TODO(jakemac): Get this merged into `benchmark_harness`. |
| 11 class AsyncBenchmarkBase { |
| 12 // Empty constructor. |
| 13 const AsyncBenchmarkBase(); |
| 14 |
| 15 // The benchmark code. |
| 16 // This function is not used, if both [warmup] and [exercise] are overwritten. |
| 17 Future run() => new Future.value(); |
| 18 |
| 19 // Runs a short version of the benchmark. By default invokes [run] once. |
| 20 Future warmup() => run(); |
| 21 |
| 22 // Exercices the benchmark. By default invokes [run] 10 times. |
| 23 Future exercise({int iterations: 10}) { |
| 24 var i = 0; |
| 25 return Future.doWhile(() { |
| 26 if (i >= iterations) return new Future.value(false); |
| 27 i++; |
| 28 return run().then((_) => true); |
| 29 }); |
| 30 } |
| 31 |
| 32 // Not measured setup code executed prior to the benchmark runs. |
| 33 Future setup() => new Future.value(); |
| 34 |
| 35 // Not measures teardown code executed after the benchark runs. |
| 36 Future teardown() => new Future.value(); |
| 37 |
| 38 // Measures the score for this benchmark by executing it repeatedly until |
| 39 // time minimum has been reached. |
| 40 static Future<double> measureFor(Function f, int minimumMillis) { |
| 41 int minimumMicros = minimumMillis * 1000; |
| 42 int iter = 0; |
| 43 Stopwatch watch = new Stopwatch(); |
| 44 watch.start(); |
| 45 int elapsed = 0; |
| 46 return Future.doWhile(() { |
| 47 if (elapsed > minimumMicros) return new Future.value(false); |
| 48 return f().then((_) { |
| 49 elapsed = watch.elapsedMicroseconds; |
| 50 iter++; |
| 51 return true; |
| 52 }); |
| 53 }).then((_) => elapsed / iter); |
| 54 } |
| 55 |
| 56 // Measures the average time to call `run` once and returns it. |
| 57 Future<double> measure({int iterations: 10}) { |
| 58 // Unmeasured setup code. |
| 59 return setup().then((_) { |
| 60 // Warmup for at least 100ms. Discard result. |
| 61 return measureFor(() => warmup(), 100); |
| 62 }).then((_) { |
| 63 // Run the benchmark for at least 2000ms. |
| 64 return measureFor(() => exercise(iterations: iterations), 2000); |
| 65 }).then((result) { |
| 66 // Tear down the test (unmeasured) and return the result divided by the |
| 67 // number of iterations. |
| 68 return teardown().then((_) => result / iterations); |
| 69 }); |
| 70 } |
| 71 } |
| OLD | NEW |