| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2011, 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 |
| 5 /** |
| 6 * Defines an asynchronous benchmark, where each iteration completes |
| 7 * asynchronously. |
| 8 */ |
| 9 // TODO(sigmund): move this to the same repo where BenchmarkBase is. |
| 10 library async_benchmark; |
| 11 |
| 12 /** The superclass from which all benchmarks inherit from. */ |
| 13 class AsyncBenchmark { |
| 14 /** Benchmark name. */ |
| 15 final String name; |
| 16 |
| 17 const AsyncBenchmark([this.name]); |
| 18 |
| 19 /** The benchmark code, invoked by [warmup] and [exercise]. */ |
| 20 Future run() => new Future.immediate(null); |
| 21 |
| 22 /** Runs a short version of the benchmark. By default invokes [run] once. */ |
| 23 Future warmup() => run(); |
| 24 |
| 25 /** Exercices the benchmark. By default invokes [run] 10 times. */ |
| 26 Future exercise() { |
| 27 int count = 10; |
| 28 Future recurse(val) { |
| 29 if (count-- <= 0) return new Future.immediate(val); |
| 30 return run().chain(recurse); |
| 31 } |
| 32 return recurse(null); |
| 33 } |
| 34 |
| 35 /** Not measured setup code executed prior to the benchmark runs. */ |
| 36 void setup() { } |
| 37 |
| 38 /** Not measures teardown code executed after the benchark runs. */ |
| 39 void teardown() { } |
| 40 |
| 41 /** |
| 42 * Measures the score for this benchmark by executing it repeately until |
| 43 * time minimum has been reached. The result is iterations per sec. |
| 44 */ |
| 45 static Future<double> measureFor(AsyncFunction f, int timeMinimum) { |
| 46 int iter = 0; |
| 47 var watch = new Stopwatch(); |
| 48 watch.start(); |
| 49 Future recurse(val) { |
| 50 int elapsed = watch.elapsedMilliseconds; |
| 51 if (elapsed < timeMinimum || iter < 32) { |
| 52 iter++; |
| 53 return f().chain(recurse); |
| 54 } |
| 55 return new Future.immediate((1000.0 * elapsed) / iter); |
| 56 } |
| 57 return recurse(null); |
| 58 } |
| 59 |
| 60 /** Measures and returns the score for the benchmark (bigger is better). */ |
| 61 Future<double> measure() { |
| 62 setup(); |
| 63 // Warmup for at least 1000ms. Discard result. |
| 64 return measureFor(warmup, 1000).chain((_) { |
| 65 // Run the benchmark for at least 1000ms. |
| 66 return measureFor(exercise, 2000).transform((result) { |
| 67 teardown(); |
| 68 return result; |
| 69 }); |
| 70 }); |
| 71 } |
| 72 } |
| 73 |
| 74 typedef Future AsyncFunction(); |
| OLD | NEW |