// Copyright 2014 The Flutter 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:convert'; import 'dart:io'; import 'package:metrics_center/src/common.dart'; const String _kTimeUnitKey = 'time_unit'; const List _kNonNumericalValueSubResults = [ kNameKey, _kTimeUnitKey, 'iterations', 'big_o', ]; /// Parse the json result of https://github.com/google/benchmark. class GoogleBenchmarkParser { /// Given a Google benchmark json output, parse its content into a list of [MetricPoint]. static Future> parse(String jsonFileName) async { final Map jsonResult = jsonDecode(File(jsonFileName).readAsStringSync()) as Map; final Map rawContext = jsonResult['context'] as Map; final Map context = rawContext.map( (String k, dynamic v) => MapEntry(k, v.toString()), ); final List points = []; for (final Map item in jsonResult['benchmarks']) { _parseAnItem(item, points, context); } return points; } } void _parseAnItem( Map item, List points, Map context, ) { final String name = item[kNameKey] as String; final Map timeUnitMap = { kUnitKey: item[_kTimeUnitKey] as String }; for (final String subResult in item.keys) { if (!_kNonNumericalValueSubResults.contains(subResult)) { num rawValue; try { rawValue = item[subResult] as num; } catch (e) { print('$subResult: ${item[subResult]} (${item[subResult].runtimeType}) is not a number'); rethrow; } final double value = rawValue is int ? rawValue.toDouble() : rawValue as double; points.add( MetricPoint( value, {kNameKey: name, kSubResultKey: subResult} ..addAll(context) ..addAll(subResult.endsWith('time') ? timeUnitMap : {}), ), ); } } }