-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathsession.py
More file actions
262 lines (237 loc) · 11.1 KB
/
session.py
File metadata and controls
262 lines (237 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from __future__ import division
from __future__ import print_function
import pytest
from .fixture import statistics
from .fixture import statistics_error
from .logger import Logger
from .table import TableResults
from .utils import NAME_FORMATTERS
from .utils import SecondsDecimal
from .utils import cached_property
from .utils import first_or_value
from .utils import get_machine_id
from .utils import load_storage
from .utils import load_timer
from .utils import safe_dumps
from .utils import short_filename
class PerformanceRegression(pytest.UsageError):
pass
class BenchmarkSession(object):
compared_mapping = None
groups = None
def __init__(self, config):
self.verbose = config.getoption("benchmark_verbose")
self.logger = Logger(self.verbose, config)
self.config = config
self.performance_regressions = []
self.benchmarks = []
self.machine_id = get_machine_id()
self.storage = load_storage(
config.getoption("benchmark_storage"),
logger=self.logger,
default_machine_id=self.machine_id,
netrc=config.getoption("benchmark_netrc")
)
self.options = dict(
min_time=SecondsDecimal(config.getoption("benchmark_min_time")),
min_rounds=config.getoption("benchmark_min_rounds"),
max_time=SecondsDecimal(config.getoption("benchmark_max_time")),
timer=load_timer(config.getoption("benchmark_timer")),
calibration_precision=config.getoption("benchmark_calibration_precision"),
disable_gc=config.getoption("benchmark_disable_gc"),
warmup=config.getoption("benchmark_warmup"),
warmup_iterations=config.getoption("benchmark_warmup_iterations"),
use_cprofile=bool(config.getoption("benchmark_cprofile")),
)
self.skip = config.getoption("benchmark_skip")
self.disabled = config.getoption("benchmark_disable") and not config.getoption("benchmark_enable")
self.cprofile_sort_by = config.getoption("benchmark_cprofile")
if config.getoption("dist", "no") != "no" and not self.skip:
self.logger.warn(
"BENCHMARK-U2",
"Benchmarks are automatically disabled because xdist plugin is active."
"Benchmarks cannot be performed reliably in a parallelized environment.",
fslocation="::"
)
self.disabled = True
if hasattr(config, "slaveinput"):
self.disabled = True
if not statistics:
self.logger.warn(
"BENCHMARK-U3",
"Benchmarks are automatically disabled because we could not import `statistics`\n\n%s" %
statistics_error,
fslocation="::"
)
self.disabled = True
self.only = config.getoption("benchmark_only")
self.sort = config.getoption("benchmark_sort")
self.columns = config.getoption("benchmark_columns")
if self.skip and self.only:
raise pytest.UsageError("Can't have both --benchmark-only and --benchmark-skip options.")
if self.disabled and self.only:
raise pytest.UsageError(
"Can't have both --benchmark-only and --benchmark-disable options. Note that --benchmark-disable is "
"automatically activated if xdist is on or you're missing the statistics dependency.")
self.group_by = config.getoption("benchmark_group_by")
self.save = config.getoption("benchmark_save")
self.autosave = config.getoption("benchmark_autosave")
self.save_data = config.getoption("benchmark_save_data")
self.json = config.getoption("benchmark_json")
self.compare = config.getoption("benchmark_compare")
self.compare_fail = config.getoption("benchmark_compare_fail")
self.name_format = NAME_FORMATTERS[config.getoption("benchmark_name")]
self.histogram = first_or_value(config.getoption("benchmark_histogram"), False)
@cached_property
def machine_info(self):
obj = self.config.hook.pytest_benchmark_generate_machine_info(config=self.config)
self.config.hook.pytest_benchmark_update_machine_info(
config=self.config,
machine_info=obj
)
return obj
def prepare_benchmarks(self):
for bench in self.benchmarks:
if bench:
compared = False
for path, compared_mapping in self.compared_mapping.items():
if bench.fullname in compared_mapping:
compared = compared_mapping[bench.fullname]
source = short_filename(path, self.machine_id)
flat_bench = bench.as_dict(include_data=False, stats=False, cprofile=self.cprofile_sort_by)
flat_bench.update(compared["stats"])
flat_bench["path"] = str(path)
flat_bench["source"] = source
if self.compare_fail:
for check in self.compare_fail:
fail = check.fails(bench, flat_bench)
if fail:
self.performance_regressions.append((self.name_format(flat_bench), fail))
yield flat_bench
flat_bench = bench.as_dict(
include_data=False,
flat=True,
cprofile=self.cprofile_sort_by,
columns=self.columns
)
flat_bench["path"] = None
flat_bench["source"] = compared and "NOW"
yield flat_bench
def save_json(self, output_json):
with self.json as fh:
fh.write(safe_dumps(output_json, ensure_ascii=True, indent=4).encode())
self.logger.info("Wrote benchmark data in: %s" % self.json, purple=True)
def handle_saving(self):
save = self.save or self.autosave
if save or self.json:
if not self.benchmarks:
self.logger.warn("BENCHMARK-U2", "Not saving anything, no benchmarks have been run!")
return
commit_info = self.config.hook.pytest_benchmark_generate_commit_info(config=self.config)
self.config.hook.pytest_benchmark_update_commit_info(config=self.config, commit_info=commit_info)
if self.json:
output_json = self.config.hook.pytest_benchmark_generate_json(
config=self.config,
benchmarks=self.benchmarks,
include_data=True,
machine_info=self.machine_info,
commit_info=commit_info,
)
self.config.hook.pytest_benchmark_update_json(
config=self.config,
benchmarks=self.benchmarks,
output_json=output_json,
)
self.save_json(output_json)
if save:
output_json = self.config.hook.pytest_benchmark_generate_json(
config=self.config,
benchmarks=self.benchmarks,
include_data=self.save_data,
machine_info=self.machine_info,
commit_info=commit_info,
)
self.config.hook.pytest_benchmark_update_json(
config=self.config,
benchmarks=self.benchmarks,
output_json=output_json,
)
self.storage.save(output_json, save)
def handle_loading(self):
compared_mapping = {}
if self.compare:
if self.compare is True:
compared_benchmarks = list(self.storage.load())[-1:]
else:
compared_benchmarks = list(self.storage.load(self.compare))
if not compared_benchmarks:
msg = "Can't compare. No benchmark files in %r" % str(self.storage)
if self.compare is True:
msg += ". Can't load the previous benchmark."
code = "BENCHMARK-C2"
else:
msg += " match %r." % self.compare
code = "BENCHMARK-C1"
self.logger.warn(code, msg, fslocation=self.storage.location)
for path, compared_benchmark in compared_benchmarks:
self.config.hook.pytest_benchmark_compare_machine_info(
config=self.config,
benchmarksession=self,
machine_info=self.machine_info,
compared_benchmark=compared_benchmark,
)
compared_mapping[path] = dict(
(bench['fullname'], bench) for bench in compared_benchmark['benchmarks']
)
self.logger.info("Comparing against benchmarks from: %s" % path, newline=False)
self.compared_mapping = compared_mapping
def finish(self):
self.handle_saving()
prepared_benchmarks = list(self.prepare_benchmarks())
if prepared_benchmarks:
self.groups = self.config.hook.pytest_benchmark_group_stats(
config=self.config,
benchmarks=prepared_benchmarks,
group_by=self.group_by
)
def display(self, tr):
if not self.groups:
return
tr.ensure_newline()
results_table = TableResults(
columns=self.columns,
sort=self.sort,
histogram=self.histogram,
name_format=self.name_format,
logger=self.logger
)
results_table.display(tr, self.groups)
self.check_regressions()
self.display_cprofile(tr)
def check_regressions(self):
if self.compare_fail and not self.compared_mapping:
raise pytest.UsageError("--benchmark-compare-fail requires valid --benchmark-compare.")
if self.performance_regressions:
self.logger.error("Performance has regressed:\n%s" % "\n".join(
"\t%s - %s" % line for line in self.performance_regressions
))
raise PerformanceRegression("Performance has regressed.")
def display_cprofile(self, tr):
if self.options["use_cprofile"]:
tr.section("cProfile information")
tr.write_line("Time in s")
for group in self.groups:
group_name, benchmarks = group
for benchmark in benchmarks:
tr.write(benchmark["fullname"], yellow=True)
if benchmark["source"]:
tr.write_line(" ({})".format((benchmark["source"])))
else:
tr.write("\n")
tr.write_line("ncalls\ttottime\tpercall\tcumtime\tpercall\tfilename:lineno(function)")
for function_info in benchmark["cprofile"]:
line = ("{ncalls_recursion}\t{tottime:.{prec}f}\t{tottime_per:.{prec}f}\t{cumtime:.{prec}f}"
"\t{cumtime_per:.{prec}f}\t{function_name}").format(
prec=4, **function_info)
tr.write_line(line)
tr.write("\n")