blob: 635dd56d16045c72d8fef16047fcc05ee50c0526 [file] [log] [blame]
Brett Cannon3b0a19e2010-07-16 19:04:29 +00001"""Benchmark some basic import use-cases.
2
3The assumption is made that this benchmark is run in a fresh interpreter and
4thus has no external changes made to import-related attributes in sys.
5
6"""
Brett Cannond382bfc2012-07-20 14:54:53 -04007from test.test_importlib import util
8from test.test_importlib.source import util as source_util
Brett Cannon5db0c942010-07-22 07:40:56 +00009import decimal
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000010import imp
11import importlib
Brett Cannon810c64d2012-05-11 11:12:00 -040012import importlib.machinery
Brett Cannon190f33c2012-01-30 19:12:29 -050013import json
Brett Cannon3b0a19e2010-07-16 19:04:29 +000014import os
15import py_compile
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000016import sys
Brett Cannon466e6a92012-02-07 09:19:12 -050017import tabnanny
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000018import timeit
19
20
Brett Cannon23cf5742009-09-03 20:45:21 +000021def bench(name, cleanup=lambda: None, *, seconds=1, repeat=3):
22 """Bench the given statement as many times as necessary until total
23 executions take one second."""
24 stmt = "__import__({!r})".format(name)
25 timer = timeit.Timer(stmt)
26 for x in range(repeat):
27 total_time = 0
28 count = 0
29 while total_time < seconds:
30 try:
31 total_time += timer.timeit(1)
32 finally:
33 cleanup()
34 count += 1
35 else:
36 # One execution too far
37 if total_time > seconds:
38 count -= 1
Brett Cannon7b9bcb82010-07-15 06:24:04 +000039 yield count // seconds
Brett Cannon23cf5742009-09-03 20:45:21 +000040
Brett Cannon3b0a19e2010-07-16 19:04:29 +000041def from_cache(seconds, repeat):
Brett Cannon23cf5742009-09-03 20:45:21 +000042 """sys.modules"""
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000043 name = '<benchmark import>'
Brett Cannon23cf5742009-09-03 20:45:21 +000044 module = imp.new_module(name)
45 module.__file__ = '<test>'
46 module.__package__ = ''
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000047 with util.uncache(name):
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000048 sys.modules[name] = module
Philip Jenveyfd0d3e52012-10-01 15:34:31 -070049 yield from bench(name, repeat=repeat, seconds=seconds)
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000050
51
Brett Cannon3b0a19e2010-07-16 19:04:29 +000052def builtin_mod(seconds, repeat):
Brett Cannon23cf5742009-09-03 20:45:21 +000053 """Built-in module"""
54 name = 'errno'
55 if name in sys.modules:
56 del sys.modules[name]
Brett Cannon7b9bcb82010-07-15 06:24:04 +000057 # Relying on built-in importer being implicit.
Philip Jenveyfd0d3e52012-10-01 15:34:31 -070058 yield from bench(name, lambda: sys.modules.pop(name), repeat=repeat,
59 seconds=seconds)
Brett Cannon6ae7a7d2009-03-30 15:53:01 +000060
61
Brett Cannon3b0a19e2010-07-16 19:04:29 +000062def source_wo_bytecode(seconds, repeat):
Brett Cannon466e6a92012-02-07 09:19:12 -050063 """Source w/o bytecode: small"""
Brett Cannon3b0a19e2010-07-16 19:04:29 +000064 sys.dont_write_bytecode = True
65 try:
66 name = '__importlib_test_benchmark__'
67 # Clears out sys.modules and puts an entry at the front of sys.path.
68 with source_util.create_modules(name) as mapping:
69 assert not os.path.exists(imp.cache_from_source(mapping[name]))
Brett Cannon810c64d2012-05-11 11:12:00 -040070 sys.meta_path.append(importlib.machinery.PathFinder)
71 loader = (importlib.machinery.SourceFileLoader,
Brett Cannoncb66eb02012-05-11 12:58:42 -040072 importlib.machinery.SOURCE_SUFFIXES, True)
Brett Cannon810c64d2012-05-11 11:12:00 -040073 sys.path_hooks.append(importlib.machinery.FileFinder.path_hook(loader))
Philip Jenveyfd0d3e52012-10-01 15:34:31 -070074 yield from bench(name, lambda: sys.modules.pop(name), repeat=repeat,
75 seconds=seconds)
Brett Cannon3b0a19e2010-07-16 19:04:29 +000076 finally:
77 sys.dont_write_bytecode = False
78
79
Brett Cannon466e6a92012-02-07 09:19:12 -050080def _wo_bytecode(module):
81 name = module.__name__
82 def benchmark_wo_bytecode(seconds, repeat):
83 """Source w/o bytecode: {}"""
84 bytecode_path = imp.cache_from_source(module.__file__)
85 if os.path.exists(bytecode_path):
86 os.unlink(bytecode_path)
87 sys.dont_write_bytecode = True
88 try:
Philip Jenveyfd0d3e52012-10-01 15:34:31 -070089 yield from bench(name, lambda: sys.modules.pop(name),
90 repeat=repeat, seconds=seconds)
Brett Cannon466e6a92012-02-07 09:19:12 -050091 finally:
92 sys.dont_write_bytecode = False
93
94 benchmark_wo_bytecode.__doc__ = benchmark_wo_bytecode.__doc__.format(name)
95 return benchmark_wo_bytecode
96
97tabnanny_wo_bytecode = _wo_bytecode(tabnanny)
98decimal_wo_bytecode = _wo_bytecode(decimal)
Brett Cannon5db0c942010-07-22 07:40:56 +000099
100
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000101def source_writing_bytecode(seconds, repeat):
Brett Cannon466e6a92012-02-07 09:19:12 -0500102 """Source writing bytecode: small"""
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000103 assert not sys.dont_write_bytecode
104 name = '__importlib_test_benchmark__'
105 with source_util.create_modules(name) as mapping:
Brett Cannon810c64d2012-05-11 11:12:00 -0400106 sys.meta_path.append(importlib.machinery.PathFinder)
107 loader = (importlib.machinery.SourceFileLoader,
Brett Cannoncb66eb02012-05-11 12:58:42 -0400108 importlib.machinery.SOURCE_SUFFIXES, True)
Brett Cannon810c64d2012-05-11 11:12:00 -0400109 sys.path_hooks.append(importlib.machinery.FileFinder.path_hook(loader))
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000110 def cleanup():
111 sys.modules.pop(name)
112 os.unlink(imp.cache_from_source(mapping[name]))
113 for result in bench(name, cleanup, repeat=repeat, seconds=seconds):
114 assert not os.path.exists(imp.cache_from_source(mapping[name]))
115 yield result
116
117
Brett Cannon466e6a92012-02-07 09:19:12 -0500118def _writing_bytecode(module):
119 name = module.__name__
120 def writing_bytecode_benchmark(seconds, repeat):
121 """Source writing bytecode: {}"""
122 assert not sys.dont_write_bytecode
123 def cleanup():
124 sys.modules.pop(name)
125 os.unlink(imp.cache_from_source(module.__file__))
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700126 yield from bench(name, cleanup, repeat=repeat, seconds=seconds)
Brett Cannon466e6a92012-02-07 09:19:12 -0500127
128 writing_bytecode_benchmark.__doc__ = (
129 writing_bytecode_benchmark.__doc__.format(name))
130 return writing_bytecode_benchmark
131
132tabnanny_writing_bytecode = _writing_bytecode(tabnanny)
133decimal_writing_bytecode = _writing_bytecode(decimal)
Brett Cannon5db0c942010-07-22 07:40:56 +0000134
135
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000136def source_using_bytecode(seconds, repeat):
Brett Cannon466e6a92012-02-07 09:19:12 -0500137 """Source w/ bytecode: small"""
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000138 name = '__importlib_test_benchmark__'
139 with source_util.create_modules(name) as mapping:
Brett Cannon810c64d2012-05-11 11:12:00 -0400140 sys.meta_path.append(importlib.machinery.PathFinder)
141 loader = (importlib.machinery.SourceFileLoader,
Brett Cannoncb66eb02012-05-11 12:58:42 -0400142 importlib.machinery.SOURCE_SUFFIXES, True)
Brett Cannon810c64d2012-05-11 11:12:00 -0400143 sys.path_hooks.append(importlib.machinery.FileFinder.path_hook(loader))
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000144 py_compile.compile(mapping[name])
145 assert os.path.exists(imp.cache_from_source(mapping[name]))
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700146 yield from bench(name, lambda: sys.modules.pop(name), repeat=repeat,
147 seconds=seconds)
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000148
149
Brett Cannon466e6a92012-02-07 09:19:12 -0500150def _using_bytecode(module):
151 name = module.__name__
152 def using_bytecode_benchmark(seconds, repeat):
153 """Source w/ bytecode: {}"""
154 py_compile.compile(module.__file__)
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700155 yield from bench(name, lambda: sys.modules.pop(name), repeat=repeat,
156 seconds=seconds)
Brett Cannon466e6a92012-02-07 09:19:12 -0500157
158 using_bytecode_benchmark.__doc__ = (
159 using_bytecode_benchmark.__doc__.format(name))
160 return using_bytecode_benchmark
161
162tabnanny_using_bytecode = _using_bytecode(tabnanny)
163decimal_using_bytecode = _using_bytecode(decimal)
Brett Cannon5db0c942010-07-22 07:40:56 +0000164
165
Brett Cannondfc32702012-02-23 19:34:35 -0500166def main(import_, options):
167 if options.source_file:
168 with options.source_file:
169 prev_results = json.load(options.source_file)
Brett Cannon190f33c2012-01-30 19:12:29 -0500170 else:
171 prev_results = {}
Brett Cannon23cf5742009-09-03 20:45:21 +0000172 __builtins__.__import__ = import_
Brett Cannon5db0c942010-07-22 07:40:56 +0000173 benchmarks = (from_cache, builtin_mod,
Brett Cannon5db0c942010-07-22 07:40:56 +0000174 source_writing_bytecode,
Brett Cannoncae10682012-02-07 09:40:33 -0500175 source_wo_bytecode, source_using_bytecode,
Brett Cannon466e6a92012-02-07 09:19:12 -0500176 tabnanny_writing_bytecode,
Brett Cannoncae10682012-02-07 09:40:33 -0500177 tabnanny_wo_bytecode, tabnanny_using_bytecode,
178 decimal_writing_bytecode,
179 decimal_wo_bytecode, decimal_using_bytecode,
180 )
Brett Cannondfc32702012-02-23 19:34:35 -0500181 if options.benchmark:
Brett Cannone3a9ae52012-01-30 19:27:51 -0500182 for b in benchmarks:
Brett Cannondfc32702012-02-23 19:34:35 -0500183 if b.__doc__ == options.benchmark:
Brett Cannone3a9ae52012-01-30 19:27:51 -0500184 benchmarks = [b]
185 break
186 else:
Brett Cannondfc32702012-02-23 19:34:35 -0500187 print('Unknown benchmark: {!r}'.format(options.benchmark,
188 file=sys.stderr))
Brett Cannone3a9ae52012-01-30 19:27:51 -0500189 sys.exit(1)
Brett Cannon5db0c942010-07-22 07:40:56 +0000190 seconds = 1
191 seconds_plural = 's' if seconds > 1 else ''
192 repeat = 3
Brett Cannon190f33c2012-01-30 19:12:29 -0500193 header = ('Measuring imports/second over {} second{}, best out of {}\n'
Brett Cannoncae10682012-02-07 09:40:33 -0500194 'Entire benchmark run should take about {} seconds\n'
195 'Using {!r} as __import__\n')
Brett Cannon190f33c2012-01-30 19:12:29 -0500196 print(header.format(seconds, seconds_plural, repeat,
Brett Cannoncae10682012-02-07 09:40:33 -0500197 len(benchmarks) * seconds * repeat, __import__))
Brett Cannon190f33c2012-01-30 19:12:29 -0500198 new_results = {}
Brett Cannon23cf5742009-09-03 20:45:21 +0000199 for benchmark in benchmarks:
200 print(benchmark.__doc__, "[", end=' ')
201 sys.stdout.flush()
202 results = []
Brett Cannon5db0c942010-07-22 07:40:56 +0000203 for result in benchmark(seconds=seconds, repeat=repeat):
Brett Cannon23cf5742009-09-03 20:45:21 +0000204 results.append(result)
205 print(result, end=' ')
206 sys.stdout.flush()
Brett Cannon3b0a19e2010-07-16 19:04:29 +0000207 assert not sys.dont_write_bytecode
Brett Cannoncbe1a4e2010-07-16 19:26:23 +0000208 print("]", "best is", format(max(results), ',d'))
Brett Cannon190f33c2012-01-30 19:12:29 -0500209 new_results[benchmark.__doc__] = results
Brett Cannondfc32702012-02-23 19:34:35 -0500210 if prev_results:
211 print('\n\nComparing new vs. old\n')
Brett Cannon190f33c2012-01-30 19:12:29 -0500212 for benchmark in benchmarks:
213 benchmark_name = benchmark.__doc__
Brett Cannondfc32702012-02-23 19:34:35 -0500214 old_result = max(prev_results[benchmark_name])
215 new_result = max(new_results[benchmark_name])
216 result = '{:,d} vs. {:,d} ({:%})'.format(new_result,
217 old_result,
218 new_result/old_result)
Brett Cannon190f33c2012-01-30 19:12:29 -0500219 print(benchmark_name, ':', result)
Brett Cannondfc32702012-02-23 19:34:35 -0500220 if options.dest_file:
221 with options.dest_file:
222 json.dump(new_results, options.dest_file, indent=2)
Brett Cannon6ae7a7d2009-03-30 15:53:01 +0000223
224
225if __name__ == '__main__':
Brett Cannon190f33c2012-01-30 19:12:29 -0500226 import argparse
Brett Cannon6ae7a7d2009-03-30 15:53:01 +0000227
Brett Cannon190f33c2012-01-30 19:12:29 -0500228 parser = argparse.ArgumentParser()
229 parser.add_argument('-b', '--builtin', dest='builtin', action='store_true',
Brett Cannon6ae7a7d2009-03-30 15:53:01 +0000230 default=False, help="use the built-in __import__")
Brett Cannondfc32702012-02-23 19:34:35 -0500231 parser.add_argument('-r', '--read', dest='source_file',
232 type=argparse.FileType('r'),
233 help='file to read benchmark data from to compare '
234 'against')
235 parser.add_argument('-w', '--write', dest='dest_file',
236 type=argparse.FileType('w'),
237 help='file to write benchmark data to')
Brett Cannone3a9ae52012-01-30 19:27:51 -0500238 parser.add_argument('--benchmark', dest='benchmark',
Brett Cannondfc32702012-02-23 19:34:35 -0500239 help='specific benchmark to run')
Brett Cannon190f33c2012-01-30 19:12:29 -0500240 options = parser.parse_args()
Brett Cannon6ae7a7d2009-03-30 15:53:01 +0000241 import_ = __import__
242 if not options.builtin:
243 import_ = importlib.__import__
244
Brett Cannondfc32702012-02-23 19:34:35 -0500245 main(import_, options)