1#
2# Copyright (C) 2017 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import json
18
19
20class GoogleBenchmarkJsonParser(object):
21    """This class parses the JSON output of Google benchmark.
22
23    Example
24    {
25      "context": {
26        "date": "2017-05-16 11:57:21",
27        "num_cpus": 4,
28        "mhz_per_cpu": 19,
29        "cpu_scaling_enabled": true,
30        "library_build_type": "release"
31      },
32      "benchmarks": [
33        {
34          "name": "BM_sendVec_binder/4",
35          "iterations": 27744,
36          "real_time": 51485,
37          "cpu_time": 23655,
38          "time_unit": "ns"
39        },
40        ...
41      ]
42    }
43
44    Attributes:
45        _benchmarks: The "benchmarks" property of the JSON object.
46    """
47
48    _BENCHMARKS = "benchmarks"
49    _NAME = "name"
50    _ITERATIONS = "iterations"
51    _REAL_TIME = "real_time"
52    _CPU_TIME = "cpu_time"
53
54    def __init__(self, json_string):
55        """Converts the JSON string to internal data structure.
56
57        Args:
58            json_string: The output of Google benchmark in JSON format.
59        """
60        json_obj = json.loads(json_string)
61        self._benchmarks = json_obj[self._BENCHMARKS]
62
63    def GetArguments(self):
64        """Returns the "name" properties with function names stripped.
65
66        Returns:
67            A list of strings.
68        """
69        args = []
70        for bm in self._benchmarks:
71            name = bm[self._NAME].split("/", 1)
72            args.append(name[1].encode("utf-8") if len(name) >= 2 else "")
73        return args
74
75    def GetRealTime(self):
76        """Returns the "real_time" properties.
77
78        Returns:
79            A list of integers.
80        """
81        return [int(float(x[self._REAL_TIME])) for x in self._benchmarks]
82
83    def ToTable(self):
84        """Returns the benchmarks in a table.
85
86        Returns:
87            A 2-dimensional list. The first row contains the column names. The
88            following rows are the benchmarks.
89        """
90        table = [[self._NAME, self._REAL_TIME, self._CPU_TIME,
91                  self._ITERATIONS]]
92        for record in self._benchmarks:
93            table.append([record[x] for x in table[0]])
94        return table
95