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 |
| 5 library dart_style.benchmark.benchmark; |
| 6 |
| 7 import 'dart:io'; |
| 8 |
| 9 import 'package:path/path.dart' as p; |
| 10 |
| 11 import 'package:dart_style/dart_style.dart'; |
| 12 |
| 13 const NUM_TRIALS = 100; |
| 14 const FORMATS_PER_TRIAL = 30; |
| 15 |
| 16 /// Note, these files use ".txt" because while they can be *parsed* correctly, |
| 17 /// they don't resolve without error. That's OK because the formatter doesn't |
| 18 /// care about that. |
| 19 final source = loadFile("before.dart.txt"); |
| 20 final expected = loadFile("after.dart.txt"); |
| 21 |
| 22 void main(List<String> args) { |
| 23 var best = 99999999.0; |
| 24 |
| 25 // Run the benchmark several times. This ensures the VM is warmed up and lets |
| 26 // us see how much variance there is. |
| 27 for (var i = 0; i <= NUM_TRIALS; i++) { |
| 28 var start = new DateTime.now(); |
| 29 |
| 30 // For a single benchmark, format the source multiple times. |
| 31 var result; |
| 32 for (var j = 0; j < FORMATS_PER_TRIAL; j++) { |
| 33 result = formatSource(); |
| 34 } |
| 35 |
| 36 var elapsed = |
| 37 new DateTime.now().difference(start).inMilliseconds / FORMATS_PER_TRIAL; |
| 38 |
| 39 // Keep track of the best run so far. |
| 40 if (elapsed >= best) continue; |
| 41 best = elapsed; |
| 42 |
| 43 // Sanity check to make sure the output is what we expect and to make sure |
| 44 // the VM doesn't optimize "dead" code away. |
| 45 if (result != expected) { |
| 46 print("Incorrect output:\n$result"); |
| 47 exit(1); |
| 48 } |
| 49 |
| 50 // Don't print the first run. It's always terrible since the VM hasn't |
| 51 // warmed up yet. |
| 52 if (i == 0) continue; |
| 53 printResult("Run ${padLeft('#$i', 3)}", elapsed); |
| 54 } |
| 55 |
| 56 printResult("Best ", best); |
| 57 } |
| 58 |
| 59 String loadFile(String name) { |
| 60 var path = p.join(p.dirname(p.fromUri(Platform.script)), name); |
| 61 return new File(path).readAsStringSync(); |
| 62 } |
| 63 |
| 64 void printResult(String label, double time) { |
| 65 print("$label: ${padLeft(time.toStringAsFixed(2), 4)}ms " |
| 66 "${'=' * ((time * 5).toInt())}"); |
| 67 } |
| 68 |
| 69 String padLeft(input, int length) { |
| 70 var result = input.toString(); |
| 71 if (result.length < length) { |
| 72 result = " " * (length - result.length) + result; |
| 73 } |
| 74 |
| 75 return result; |
| 76 } |
| 77 |
| 78 String formatSource() { |
| 79 var formatter = new DartFormatter(); |
| 80 return formatter.format(source); |
| 81 } |
OLD | NEW |