Brett Cannon | 6ae7a7d | 2009-03-30 15:53:01 +0000 | [diff] [blame^] | 1 | from . import util |
| 2 | from .source import util as source_util |
| 3 | import gc |
| 4 | import decimal |
| 5 | import imp |
| 6 | import importlib |
| 7 | import sys |
| 8 | import timeit |
| 9 | |
| 10 | |
| 11 | def bench_cache(import_, repeat, number): |
| 12 | """Measure the time it takes to pull from sys.modules.""" |
| 13 | name = '<benchmark import>' |
| 14 | with util.uncache(name): |
| 15 | module = imp.new_module(name) |
| 16 | sys.modules[name] = module |
| 17 | runs = [] |
| 18 | for x in range(repeat): |
| 19 | start_time = timeit.default_timer() |
| 20 | for y in range(number): |
| 21 | import_(name) |
| 22 | end_time = timeit.default_timer() |
| 23 | runs.append(end_time - start_time) |
| 24 | return min(runs) |
| 25 | |
| 26 | |
| 27 | def bench_importing_source(import_, repeat, number, loc=100000): |
| 28 | """Measure importing source from disk. |
| 29 | |
| 30 | For worst-case scenario, the line endings are \\r\\n and thus require |
| 31 | universal newline translation. |
| 32 | |
| 33 | """ |
| 34 | name = '__benchmark' |
| 35 | with source_util.create_modules(name) as mapping: |
| 36 | with open(mapping[name], 'w') as file: |
| 37 | for x in range(loc): |
| 38 | file.write("{0}\r\n".format(x)) |
| 39 | with util.import_state(path=[mapping['.root']]): |
| 40 | runs = [] |
| 41 | for x in range(repeat): |
| 42 | start_time = timeit.default_timer() |
| 43 | for y in range(number): |
| 44 | try: |
| 45 | import_(name) |
| 46 | finally: |
| 47 | del sys.modules[name] |
| 48 | end_time = timeit.default_timer() |
| 49 | runs.append(end_time - start_time) |
| 50 | return min(runs) |
| 51 | |
| 52 | |
| 53 | def main(import_): |
| 54 | args = [('sys.modules', bench_cache, 5, 500000), |
| 55 | ('source', bench_importing_source, 5, 10000)] |
| 56 | test_msg = "{test}, {number} times (best of {repeat}):" |
| 57 | result_msg = "{result:.2f} secs" |
| 58 | gc.disable() |
| 59 | try: |
| 60 | for name, meth, repeat, number in args: |
| 61 | result = meth(import_, repeat, number) |
| 62 | print(test_msg.format(test=name, repeat=repeat, |
| 63 | number=number).ljust(40), |
| 64 | result_msg.format(result=result).rjust(10)) |
| 65 | finally: |
| 66 | gc.enable() |
| 67 | |
| 68 | |
| 69 | if __name__ == '__main__': |
| 70 | import optparse |
| 71 | |
| 72 | parser = optparse.OptionParser() |
| 73 | parser.add_option('-b', '--builtin', dest='builtin', action='store_true', |
| 74 | default=False, help="use the built-in __import__") |
| 75 | options, args = parser.parse_args() |
| 76 | if args: |
| 77 | raise RuntimeError("unrecognized args: {0}".format(args)) |
| 78 | import_ = __import__ |
| 79 | if not options.builtin: |
| 80 | import_ = importlib.__import__ |
| 81 | |
| 82 | main(import_) |