/
test_timeit.py
467 lines (380 loc) · 16.2 KB
/
test_timeit.py
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import errno
import os.path
import re
import shutil
import sys
import tempfile
import textwrap
import unittest
from pathlib import Path
import pyperf
from pyperf import tests
from pyperf._timeit import Timer
PERF_TIMEIT = (sys.executable, '-m', 'pyperf', 'timeit')
# We only need a statement taking longer than 0 nanosecond
FAST_BENCH_ARGS = ('--debug-single-value',
'-s', 'import time',
'time.sleep(1e-6)')
FAST_MIN_TIME = 1e-6
# test with a least with two values
COMPARE_BENCH = ('-l1', '-p1', '-w0', '-n3',
'-s', 'import time',
'time.sleep(1e-6)')
SLEEP = 'time.sleep(1e-3)'
# The perfect timing is 1 ms +- 0 ms, but tolerate large differences on busy
# systems. The unit test doesn't test the system but more the output format.
MIN_VALUE = 0.9 # ms
MAX_VALUE = 50.0 # ms
MIN_MEAN = MIN_VALUE
MAX_MEAN = MAX_VALUE / 2
MAX_STD_DEV = 10.0 # ms
PYPY = pyperf.python_implementation() == 'pypy'
def identity(x):
return x
def reindent(src, indent):
return src.replace("\n", "\n" + " " * indent)
def template_output(stmt='pass', setup='pass', teardown='pass', init=''):
if PYPY:
template = textwrap.dedent("""
def inner(_it, _timer{init}):
{setup}
_t0 = _timer()
while _it > 0:
_it -= 1
{stmt}
_t1 = _timer()
{teardown}
return _t1 - _t0
""")
else:
template = textwrap.dedent("""
def inner(_it, _timer{init}):
{setup}
_t0 = _timer()
for _i in _it:
{stmt}
_t1 = _timer()
{teardown}
return _t1 - _t0
""")
return template.format(init=init,
stmt=reindent(stmt, 8),
setup=reindent(setup, 4),
teardown=reindent(teardown, 4))
class TestTimeit(unittest.TestCase):
@unittest.skipIf(sys.platform == 'win32',
'https://github.com/psf/pyperf/issues/97')
def test_worker_verbose(self):
args = ('--worker',
'-w', '1',
'-n', '2',
'-l', '1',
'--min-time', '0.001',
'--metadata',
'-v',
'-s', 'import time',
SLEEP)
args = PERF_TIMEIT + args
cmd = tests.get_output(args)
self.assertEqual(cmd.returncode, 0)
self.assertEqual(cmd.stderr, '')
match = re.search(r'Warmup 1: ([0-9.]+) ms \(loops: 1, raw: [0-9.]+ ms\)\n'
r'\n'
r'Value 1: ([0-9.]+) ms\n'
r'Value 2: ([0-9.]+) ms\n'
r'\n'
r'Metadata:\n'
r'(- .*\n)+'
r'\n'
r'Mean \+- std dev: (?P<mean>[0-9.]+) ms \+-'
' (?P<mad>[0-9.]+) ms\n'
r'$',
cmd.stdout)
self.assertIsNotNone(match, repr(cmd.stdout))
values = [float(match.group(i)) for i in range(1, 4)]
for value in values:
self.assertTrue(MIN_VALUE <= value <= MAX_VALUE,
repr(value))
mean = float(match.group('mean'))
self.assertTrue(MIN_MEAN <= mean <= MAX_MEAN, mean)
mad = float(match.group('mad'))
self.assertLessEqual(mad, MAX_STD_DEV)
def test_cli(self):
args = ('-p', '2',
'-w', '1',
'-n', '3',
'-l', '4',
'--min-time', '0.001',
'-s', 'import time',
SLEEP)
args = PERF_TIMEIT + args
cmd = tests.get_output(args)
self.assertEqual(cmd.returncode, 0)
self.assertEqual(cmd.stderr, '')
# ignore lines before to ignore random warnings like
# "ERROR: the benchmark is very unstable"
match = re.search(r'Mean \+- std dev: (?P<mean>[0-9.]+) ms'
r' \+- (?P<mad>[0-9.]+) ms'
r'$',
cmd.stdout.rstrip())
self.assertIsNotNone(match, repr(cmd.stdout))
# Tolerate large differences on busy systems
mean = float(match.group('mean'))
self.assertTrue(MIN_MEAN <= mean <= MAX_MEAN, mean)
mad = float(match.group('mad'))
self.assertLessEqual(mad, MAX_STD_DEV)
def run_timeit(self, args):
cmd = tests.get_output(args)
self.assertEqual(cmd.returncode, 0, cmd.stdout + cmd.stderr)
return cmd.stdout
def run_timeit_bench(self, args):
with tests.temporary_directory() as tmpdir:
filename = os.path.join(tmpdir, 'test.json')
args += ('--output', filename)
stdout = self.run_timeit(args)
bench = pyperf.Benchmark.load(filename)
return (bench, stdout)
def test_verbose_output(self):
args = ('-p', '2',
'-w', '1',
'-n', '3',
# don't pass --loops to test calibration
'--min-time', '0.001',
'-s', 'import time',
'--verbose',
SLEEP)
args = PERF_TIMEIT + args
# Don't check the exact output, only check that the verbose
# mode doesn't fail with an error (non-zero exist code)
self.run_timeit_bench(args)
def test_bench(self):
loops = 4
args = ('-p', '2',
'-w', '1',
'-n', '3',
'-l', str(loops),
'--min-time', '0.001',
'-s', 'import time',
SLEEP)
args = PERF_TIMEIT + args
bench, stdout = self.run_timeit_bench(args)
# FIXME: skipped test, since calibration continues during warmup
if not pyperf.python_has_jit():
for run in bench.get_runs():
self.assertEqual(run.get_total_loops(), 4)
runs = bench.get_runs()
self.assertEqual(len(runs), 2)
for run in runs:
self.assertIsInstance(run, pyperf.Run)
raw_values = run._get_raw_values(warmups=True)
self.assertEqual(len(raw_values), 4)
for raw_value in raw_values:
ms = (raw_value / loops) * 1e3
self.assertTrue(MIN_VALUE <= ms <= MAX_VALUE, ms)
def test_append(self):
with tests.temporary_directory() as tmpdir:
filename = os.path.join(tmpdir, 'test.json')
args = PERF_TIMEIT + ('--append', filename) + FAST_BENCH_ARGS
self.run_timeit(args)
bench = pyperf.Benchmark.load(filename)
self.assertEqual(bench.get_nvalue(), 1)
self.run_timeit(args)
bench = pyperf.Benchmark.load(filename)
self.assertEqual(bench.get_nvalue(), 2)
def test_cli_snippet_error(self):
args = PERF_TIMEIT + ('x+1',)
cmd = tests.get_output(args)
self.assertEqual(cmd.returncode, 1)
self.assertIn('Traceback (most recent call last):', cmd.stderr)
self.assertIn("NameError", cmd.stderr)
# When the PyPy program is copied, it fails with "Library path not found"
@unittest.skipIf(pyperf.python_implementation() == 'pypy',
'pypy program cannot be copied')
@unittest.skipIf(sys.platform == 'win32',
'https://github.com/psf/pyperf/issues/97')
def test_python_option(self):
# Ensure that paths are absolute
paths = [os.path.realpath(path) for path in sys.path]
env = dict(os.environ, PYTHONPATH=os.pathsep.join(paths))
tmp_exe = tempfile.mktemp()
try:
shutil.copy2(sys.executable, tmp_exe)
# Run benchmark to check if --python works
args = ('--metadata',
'--python', tmp_exe)
args = PERF_TIMEIT + args + FAST_BENCH_ARGS
cmd = tests.get_output(args, env=env)
finally:
try:
os.unlink(tmp_exe)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
tmp_exe = Path(tmp_exe).resolve()
self.assertEqual(cmd.returncode, 0, repr(cmd.stdout + cmd.stderr))
self.assertIn("python_executable: %s" % tmp_exe, cmd.stdout)
def test_name(self):
name = 'myname'
args = PERF_TIMEIT + ('--name', name) + FAST_BENCH_ARGS
bench, stdout = self.run_timeit_bench(args)
self.assertEqual(bench.get_name(), name)
self.assertRegex(stdout, re.compile('^%s' % name, flags=re.MULTILINE))
def test_inner_loops(self):
inner_loops = 17
args = PERF_TIMEIT + ('--inner-loops', str(inner_loops)) + FAST_BENCH_ARGS
bench, stdout = self.run_timeit_bench(args)
metadata = bench.get_metadata()
self.assertEqual(metadata['inner_loops'], inner_loops)
def test_compare_to(self):
args = ('--compare-to', sys.executable,
'--python-names=ref:changed')
args = PERF_TIMEIT + args + COMPARE_BENCH
cmd = tests.get_output(args)
# ".*" and DOTALL ignore stability warnings
expected = textwrap.dedent(r'''
ref: \. [0-9.]+ (?:ms|us) \+- [0-9.]+ (?:ms|us).*
changed: \. [0-9.]+ (?:ms|us) \+- [0-9.]+ (?:ms|us).*
Mean \+- std dev: \[ref\] .* -> \[changed\] .*: (?:[0-9]+\.[0-9][0-9]x (?:faster|slower)|no change)
''').strip()
expected = re.compile(expected, flags=re.DOTALL)
self.assertRegex(cmd.stdout, expected)
def test_compare_to_verbose(self):
args = PERF_TIMEIT + ('--compare-to', sys.executable, '--verbose')
args += COMPARE_BENCH
cmd = tests.get_output(args)
expected = textwrap.dedent(r'''
Benchmark .*
==========+
.*
Mean \+- std dev: .*
Benchmark .*
==========+
.*
Mean \+- std dev: .*
Compare
=======
Mean \+- std dev: .* -> .*: (?:[0-9]+\.[0-9][0-9]x (?:faster|slower)|no change)
''').strip()
expected = re.compile(expected, flags=re.DOTALL)
self.assertRegex(cmd.stdout, expected)
def test_compare_to_quiet(self):
args = PERF_TIMEIT + ('--compare-to', sys.executable, '--quiet')
args += COMPARE_BENCH
cmd = tests.get_output(args)
expected = r'(?:Mean \+- std dev: .* -> .*: (?:[0-9]+\.[0-9][0-9]x (?:faster|slower)|no change)|Not significant!)'
self.assertRegex(cmd.stdout, expected)
def test_duplicate(self):
sleep = 1e-3
duplicate = 10
args = PERF_TIMEIT
args += ('-n3', '-p1',
'--duplicate', str(duplicate), '--loops', '1',
'-s', 'import time', 'time.sleep(%s)' % sleep)
bench, stdout = self.run_timeit_bench(args)
metadata = bench.get_metadata()
self.assertEqual(metadata['timeit_duplicate'], duplicate)
for raw_value in bench._get_raw_values():
self.assertGreaterEqual(raw_value, sleep * duplicate)
def test_teardown_single_line(self):
args = PERF_TIMEIT + ('--teardown', 'assert 2 == 2') + FAST_BENCH_ARGS
cmd = tests.get_output(args)
self.assertEqual(cmd.returncode, 0, cmd.stdout + cmd.stderr)
def test_teardown_multi_line(self):
args = PERF_TIMEIT + ('--teardown', 'assert 2 == 2',
'--teardown', 'assert 2 == 2') + FAST_BENCH_ARGS
cmd = tests.get_output(args)
self.assertEqual(cmd.returncode, 0, cmd.stdout + cmd.stderr)
class TimerTests(unittest.TestCase):
def test_raises_if_setup_is_missing(self):
with self.assertRaises(ValueError) as cm:
Timer(setup=None)
err = cm.exception
self.assertEqual(str(err), 'setup is neither a string nor callable')
def test_raises_if_stmt_is_missing(self):
with self.assertRaises(ValueError) as cm:
Timer(stmt=None)
err = cm.exception
self.assertEqual(str(err), 'stmt is neither a string nor callable')
def test_raises_if_teardown_is_missing(self):
with self.assertRaises(ValueError) as cm:
Timer(teardown=None)
err = cm.exception
self.assertEqual(str(err), 'teardown is neither a string nor callable')
def test_raises_if_setup_contains_invalid_syntax(self):
with self.assertRaises(SyntaxError) as cm:
Timer(setup='foo = 1, 2, *')
err = cm.exception
self.assertTrue('invalid syntax' in str(err))
def test_raises_if_stmt_contains_invalid_syntax(self):
with self.assertRaises(SyntaxError) as cm:
Timer(stmt='foo = 1, 2, *')
err = cm.exception
self.assertTrue('invalid syntax' in str(err))
def test_raises_if_teardown_contains_invalid_syntax(self):
with self.assertRaises(SyntaxError) as cm:
Timer(teardown='foo = 1, 2, *')
err = cm.exception
self.assertTrue('invalid syntax' in str(err))
def test_raises_if_setup_and_stmt_contain_invalid_syntax(self):
with self.assertRaises(SyntaxError) as cm:
Timer(setup="foo = 'bar', \\ ", stmt="bar = 'baz'")
err = cm.exception
if PYPY:
self.assertTrue("Unknown character" in str(err))
else:
self.assertTrue('unexpected character after line' in str(err))
def test_raises_if_stmt_and_teardown_contain_invalid_syntax(self):
with self.assertRaises(SyntaxError) as cm:
Timer(stmt="foo = 'bar', \\ ", teardown="bar = 'baz'")
err = cm.exception
if PYPY:
self.assertTrue("Unknown character" in str(err))
else:
self.assertTrue('unexpected character after line' in str(err))
def test_returns_valid_template_if_setup_is_str(self):
setup = "foo = 'bar'\nbar = 'baz'"
timer = Timer(setup=setup)
self.assertEqual(timer.src, template_output(setup=setup))
def test_returns_valid_template_if_stmt_is_str(self):
stmt = "foo = 'bar'\nbar = 'baz'"
timer = Timer(stmt=stmt)
self.assertEqual(timer.src, template_output(stmt=stmt))
def test_returns_valid_template_if_teardown_is_str(self):
teardown = "foo = 'bar'\nbar = 'baz'"
timer = Timer(teardown=teardown)
self.assertEqual(timer.src, template_output(teardown=teardown))
def test_returns_valid_template_with_all_str_params(self):
setup, stmt, teardown = "a = 1 + 2", "b = 2 + 3", "c = 3 + 4"
timer = Timer(setup=setup, stmt=stmt, teardown=teardown)
self.assertEqual(timer.src, template_output(stmt, setup, teardown))
def test_returns_valid_template_if_setup_is_code(self):
setup = identity
timer = Timer(setup=setup)
output = template_output(setup='_setup()', init=', _setup=_setup')
self.assertEqual(timer.src, output)
self.assertDictEqual({'_setup': setup}, timer.local_ns)
def test_returns_valid_template_if_stmt_is_code(self):
stmt = identity
timer = Timer(stmt=stmt)
output = template_output(stmt='_stmt()', init=', _stmt=_stmt')
self.assertEqual(timer.src, output)
self.assertDictEqual({'_stmt': stmt}, timer.local_ns)
def test_returns_valid_template_if_teardown_is_code(self):
teardown = identity
timer = Timer(teardown=teardown)
output = template_output(teardown='_teardown()',
init=', _teardown=_teardown')
self.assertEqual(timer.src, output)
self.assertDictEqual({'_teardown': teardown}, timer.local_ns)
def test_returns_valid_template_with_all_callable_params(self):
setup, stmt, teardown = identity, identity, identity
timer = Timer(setup=setup, stmt=stmt, teardown=teardown)
output = template_output(setup='_setup()', stmt='_stmt()',
teardown='_teardown()',
init=', _setup=_setup, _stmt=_stmt, '
'_teardown=_teardown')
self.assertEqual(timer.src, output)
self.assertDictEqual({'_setup': setup, '_stmt': stmt,
'_teardown': teardown}, timer.local_ns)
if __name__ == "__main__":
unittest.main()