Class for timing execution speed of small code snippets. The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to 'pass'; the timer function is platform-dependent (see module doc string). If 'globals' i
| 85 | |
| 86 | |
| 87 | class Timer: |
| 88 | """Class for timing execution speed of small code snippets. |
| 89 | |
| 90 | The constructor takes a statement to be timed, an additional |
| 91 | statement used for setup, and a timer function. Both statements |
| 92 | default to 'pass'; the timer function is platform-dependent (see |
| 93 | module doc string). If 'globals' is specified, the code will be |
| 94 | executed within that namespace (as opposed to inside timeit's |
| 95 | namespace). |
| 96 | |
| 97 | To measure the execution time of the first statement, use the |
| 98 | timeit() method. The repeat() method is a convenience to call |
| 99 | timeit() multiple times and return a list of results. |
| 100 | |
| 101 | The statements may contain newlines, as long as they don't contain |
| 102 | multi-line string literals. |
| 103 | """ |
| 104 | |
| 105 | def __init__(self, stmt="pass", setup="pass", timer=default_timer, |
| 106 | globals=None): |
| 107 | """Constructor. See class doc string.""" |
| 108 | self.timer = timer |
| 109 | local_ns = {} |
| 110 | global_ns = _globals() if globals is None else globals |
| 111 | init = '' |
| 112 | if isinstance(setup, str): |
| 113 | # Check that the code can be compiled outside a function |
| 114 | compile(setup, dummy_src_name, "exec") |
| 115 | stmtprefix = setup + '\n' |
| 116 | setup = reindent(setup, 4) |
| 117 | elif callable(setup): |
| 118 | local_ns['_setup'] = setup |
| 119 | init += ', _setup=_setup' |
| 120 | stmtprefix = '' |
| 121 | setup = '_setup()' |
| 122 | else: |
| 123 | raise ValueError("setup is neither a string nor callable") |
| 124 | if isinstance(stmt, str): |
| 125 | # Check that the code can be compiled outside a function |
| 126 | compile(stmtprefix + stmt, dummy_src_name, "exec") |
| 127 | stmt = reindent(stmt, 8) |
| 128 | elif callable(stmt): |
| 129 | local_ns['_stmt'] = stmt |
| 130 | init += ', _stmt=_stmt' |
| 131 | stmt = '_stmt()' |
| 132 | else: |
| 133 | raise ValueError("stmt is neither a string nor callable") |
| 134 | src = template.format(stmt=stmt, setup=setup, init=init) |
| 135 | self.src = src # Save for traceback display |
| 136 | code = compile(src, dummy_src_name, "exec") |
| 137 | exec(code, global_ns, local_ns) |
| 138 | self.inner = local_ns["inner"] |
| 139 | |
| 140 | def print_exc(self, file=None, **kwargs): |
| 141 | """Helper to print a traceback from the timed code. |
| 142 | |
| 143 | Typical use: |
| 144 |
no outgoing calls
no test coverage detected
searching dependent graphs…