blob: 162c5770a9c50f0381c530de10131ce0f7bb641b [file] [log] [blame]
Joe Onorato88ede352023-12-19 02:56:38 +00001#!/usr/bin/env python3
2# Copyright (C) 2023 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
16import sys
17if __name__ == "__main__":
18 sys.dont_write_bytecode = True
19
20import argparse
21import dataclasses
22import datetime
23import json
24import os
25import pathlib
26import statistics
27import zoneinfo
28
29import pretty
30import utils
31
32# TODO:
33# - Flag if the last postroll build was more than 15 seconds or something. That's
34# an indicator that something is amiss.
35# - Add a mode to print all of the values for multi-iteration runs
36# - Add a flag to reorder the tags
37# - Add a flag to reorder the headers in order to show grouping more clearly.
38
39
40def FindSummaries(args):
41 def find_summaries(directory):
42 return [str(p.resolve()) for p in pathlib.Path(directory).glob("**/summary.json")]
43 if not args:
44 # If they didn't give an argument, use the default dir
45 root = utils.get_root()
46 if not root:
47 return []
48 return find_summaries(root.joinpath("..", utils.DEFAULT_REPORT_DIR))
49 results = list()
50 for arg in args:
51 if os.path.isfile(arg):
52 # If it's a file add that
53 results.append(arg)
54 elif os.path.isdir(arg):
55 # If it's a directory, find all of the files there
56 results += find_summaries(arg)
57 else:
58 sys.stderr.write(f"Invalid summary argument: {arg}\n")
59 sys.exit(1)
60 return sorted(list(results))
61
62
63def LoadSummary(filename):
64 with open(filename) as f:
65 return json.load(f)
66
67# Columns:
68# Date
69# Branch
70# Tag
71# --
72# Lunch
73# Rows:
74# Benchmark
75
Joe Onorato88ede352023-12-19 02:56:38 +000076def lunch_str(d):
77 "Convert a lunch dict to a string"
78 return f"{d['TARGET_PRODUCT']}-{d['TARGET_RELEASE']}-{d['TARGET_BUILD_VARIANT']}"
79
80def group_by(l, key):
81 "Return a list of tuples, grouped by key, sorted by key"
82 result = {}
83 for item in l:
84 result.setdefault(key(item), []).append(item)
85 return [(k, v) for k, v in result.items()]
86
87
88class Table:
Joe Onorato6b408262024-01-19 16:35:02 +000089 def __init__(self, row_title, fixed_titles=[]):
Joe Onorato88ede352023-12-19 02:56:38 +000090 self._data = {}
91 self._rows = []
92 self._cols = []
Joe Onorato6b408262024-01-19 16:35:02 +000093 self._fixed_cols = {}
94 self._titles = [row_title] + fixed_titles
Joe Onorato88ede352023-12-19 02:56:38 +000095
96 def Set(self, column_key, row_key, data):
97 self._data[(column_key, row_key)] = data
98 if not column_key in self._cols:
99 self._cols.append(column_key)
100 if not row_key in self._rows:
101 self._rows.append(row_key)
102
Joe Onorato6b408262024-01-19 16:35:02 +0000103 def SetFixedCol(self, row_key, columns):
104 self._fixed_cols[row_key] = columns
105
Joe Onorato88ede352023-12-19 02:56:38 +0000106 def Write(self, out):
107 table = []
108 # Expand the column items
109 for row in zip(*self._cols):
110 if row.count(row[0]) == len(row):
111 continue
Joe Onorato6b408262024-01-19 16:35:02 +0000112 table.append([""] * len(self._titles) + [col for col in row])
Joe Onorato88ede352023-12-19 02:56:38 +0000113 if table:
Joe Onorato6b408262024-01-19 16:35:02 +0000114 # Update the last row of the header with title and add separator
115 for i in range(len(self._titles)):
116 table[len(table)-1][i] = self._titles[i]
Joe Onorato88ede352023-12-19 02:56:38 +0000117 table.append(pretty.SEPARATOR)
118 # Populate the data
119 for row in self._rows:
Joe Onorato6b408262024-01-19 16:35:02 +0000120 table.append([str(row)]
121 + self._fixed_cols[row]
122 + [str(self._data.get((col, row), "")) for col in self._cols])
123 out.write(pretty.FormatTable(table, alignments="LL"))
Joe Onorato88ede352023-12-19 02:56:38 +0000124
125
126def format_duration_sec(ns):
127 "Format a duration in ns to second precision"
128 sec = round(ns / 1000000000)
129 h, sec = divmod(sec, 60*60)
130 m, sec = divmod(sec, 60)
131 result = ""
132 if h > 0:
133 result += f"{h:2d}h "
134 if h > 0 or m > 0:
135 result += f"{m:2d}m "
136 return result + f"{sec:2d}s"
137
Joe Onorato67c944b2023-12-21 13:29:18 -0800138
Joe Onorato88ede352023-12-19 02:56:38 +0000139def main(argv):
140 parser = argparse.ArgumentParser(
141 prog="format_benchmarks",
142 allow_abbrev=False, # Don't let people write unsupportable scripts.
143 description="Print analysis tables for benchmarks")
144
Joe Onorato67c944b2023-12-21 13:29:18 -0800145 parser.add_argument("--tags", nargs="*",
146 help="The tags to print, in order.")
147
Joe Onorato88ede352023-12-19 02:56:38 +0000148 parser.add_argument("summaries", nargs="*",
149 help="A summary.json file or a directory in which to look for summaries.")
150
151 args = parser.parse_args()
152
153 # Load the summaries
154 summaries = [(s, LoadSummary(s)) for s in FindSummaries(args.summaries)]
155
156 # Convert to MTV time
157 for filename, s in summaries:
158 dt = datetime.datetime.fromisoformat(s["start_time"])
159 dt = dt.astimezone(zoneinfo.ZoneInfo("America/Los_Angeles"))
160 s["datetime"] = dt
161 s["date"] = datetime.date(dt.year, dt.month, dt.day)
162
Joe Onorato67c944b2023-12-21 13:29:18 -0800163 # Filter out tags we don't want
164 if args.tags:
165 summaries = [(f, s) for f, s in summaries if s.get("tag", "") in args.tags]
166
167 # If they supplied tags, sort in that order, otherwise sort by tag
168 if args.tags:
169 tagsort = lambda tag: args.tags.index(tag)
170 else:
171 tagsort = lambda tag: tag
172
Joe Onorato88ede352023-12-19 02:56:38 +0000173 # Sort the summaries
Joe Onorato67c944b2023-12-21 13:29:18 -0800174 summaries.sort(key=lambda s: (s[1]["date"], s[1]["branch"], tagsort(s[1]["tag"])))
Joe Onorato88ede352023-12-19 02:56:38 +0000175
176 # group the benchmarks by column and iteration
177 def bm_key(b):
178 return (
179 lunch_str(b["lunch"]),
180 )
181 for filename, summary in summaries:
182 summary["columns"] = [(key, group_by(bms, lambda b: b["id"])) for key, bms
183 in group_by(summary["benchmarks"], bm_key)]
184
185 # Build the table
Joe Onorato6b408262024-01-19 16:35:02 +0000186 table = Table("Benchmark", ["Rebuild"])
Joe Onorato88ede352023-12-19 02:56:38 +0000187 for filename, summary in summaries:
188 for key, column in summary["columns"]:
189 for id, cell in column:
190 duration_ns = statistics.median([b["duration_ns"] for b in cell])
Joe Onorato6b408262024-01-19 16:35:02 +0000191 table.SetFixedCol(cell[0]["title"], [" ".join(cell[0]["modules"])])
Joe Onorato519c9da2024-01-02 16:46:26 -0800192 table.Set(tuple([summary["date"].strftime("%Y-%m-%d"),
Joe Onorato88ede352023-12-19 02:56:38 +0000193 summary["branch"],
194 summary["tag"]]
195 + list(key)),
196 cell[0]["title"], format_duration_sec(duration_ns))
197
198 table.Write(sys.stdout)
199
200if __name__ == "__main__":
201 main(sys.argv)
202