1// Copyright 2017 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5import 'dart:convert' show json; 6 7import 'package:meta/meta.dart'; 8 9/// This class knows how to format benchmark results for machine and human 10/// consumption. 11/// 12 13/// Example: 14/// 15/// BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); 16/// printer.add( 17/// description: 'Average frame time', 18/// value: averageFrameTime, 19/// unit: 'ms', 20/// name: 'average_frame_time', 21/// ); 22/// printer.printToStdout(); 23/// 24class BenchmarkResultPrinter { 25 26 final List<_BenchmarkResult> _results = <_BenchmarkResult>[]; 27 28 /// Adds a benchmark result to the list of results. 29 /// 30 /// [description] is a human-readable description of the result. [value] is a 31 /// result value. [unit] is the unit of measurement, such as "ms", "km", "h". 32 /// [name] is a computer-readable name of the result used as a key in the JSON 33 /// serialization of the results. 34 void addResult({ @required String description, @required double value, @required String unit, @required String name }) { 35 _results.add(_BenchmarkResult(description, value, unit, name)); 36 } 37 38 /// Prints the results added via [addResult] to standard output, once as JSON 39 /// for computer consumption and once formatted as plain text for humans. 40 void printToStdout() { 41 // IMPORTANT: keep these values in sync with dev/devicelab/bin/tasks/microbenchmarks.dart 42 const String jsonStart = '================ RESULTS ================'; 43 const String jsonEnd = '================ FORMATTED =============='; 44 const String jsonPrefix = ':::JSON:::'; 45 46 print(jsonStart); 47 print('$jsonPrefix ${_printJson()}'); 48 print(jsonEnd); 49 print(_printPlainText()); 50 } 51 52 String _printJson() { 53 final Map<String, double> results = <String, double>{}; 54 for (_BenchmarkResult result in _results) { 55 results[result.name] = result.value; 56 } 57 return json.encode(results); 58 } 59 60 String _printPlainText() { 61 final StringBuffer buf = StringBuffer(); 62 for (_BenchmarkResult result in _results) { 63 buf.writeln('${result.description}: ${result.value.toStringAsFixed(1)} ${result.unit}'); 64 } 65 return buf.toString(); 66 } 67} 68 69class _BenchmarkResult { 70 _BenchmarkResult(this.description, this.value, this.unit, this.name); 71 72 /// Human-readable description of the result, e.g. "Average frame time". 73 final String description; 74 75 /// Result value that in agreement with [unit]. 76 final double value; 77 78 /// Unit of measurement that is in agreement with [value]. 79 final String unit; 80 81 /// Computer-readable name of the result. 82 final String name; 83} 84