| 1 |
|
| 2 |
|
| 3 |
"""Tool for measuring execution time of small code snippets. |
| 4 |
|
| 5 |
This module avoids a number of common traps for measuring execution |
| 6 |
times. See also Tim Peters' introduction to the Algorithms chapter in |
| 7 |
the Python Cookbook, published by O'Reilly. |
| 8 |
|
| 9 |
Library usage: see the Timer class. |
| 10 |
|
| 11 |
Command line usage: |
| 12 |
python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement] |
| 13 |
|
| 14 |
Options: |
| 15 |
-n/--number N: how many times to execute 'statement' (default: see below) |
| 16 |
-r/--repeat N: how many times to repeat the timer (default 5) |
| 17 |
-s/--setup S: statement to be executed once initially (default 'pass'). |
| 18 |
Execution time of this setup statement is NOT timed. |
| 19 |
-p/--process: use time.process_time() (default is time.perf_counter()) |
| 20 |
-v/--verbose: print raw timing results; repeat for more digits precision |
| 21 |
-u/--unit: set the output time unit (nsec, usec, msec, or sec) |
| 22 |
-h/--help: print this usage message and exit |
| 23 |
--: separate options from statement, use when statement starts with - |
| 24 |
statement: statement to be timed (default 'pass') |
| 25 |
|
| 26 |
A multi-line statement may be given by specifying each line as a |
| 27 |
separate argument; indented lines are possible by enclosing an |
| 28 |
argument in quotes and using leading spaces. Multiple -s options are |
| 29 |
treated similarly. |
| 30 |
|
| 31 |
If -n is not given, a suitable number of loops is calculated by trying |
| 32 |
increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the |
| 33 |
total time is at least 0.2 seconds. |
| 34 |
|
| 35 |
Note: there is a certain baseline overhead associated with executing a |
| 36 |
pass statement. It differs between versions. The code here doesn't try |
| 37 |
to hide it, but you should be aware of it. The baseline overhead can be |
| 38 |
measured by invoking the program without arguments. |
| 39 |
|
| 40 |
Classes: |
| 41 |
|
| 42 |
Timer |
| 43 |
|
| 44 |
Functions: |
| 45 |
|
| 46 |
timeit(string, string) -> float |
| 47 |
repeat(string, string) -> list |
| 48 |
default_timer() -> float |
| 49 |
|
| 50 |
""" |
| 51 |
|
| 52 |
import gc |
| 53 |
import itertools |
| 54 |
import math |
| 55 |
import sys |
| 56 |
import time |
| 57 |
|
| 58 |
__all__ = ["Timer", "timeit", "repeat", "default_timer"] |
| 59 |
|
| 60 |
dummy_src_name = "<timeit-src>" |
| 61 |
default_number = 1000000 |
| 62 |
default_repeat = 7 |
| 63 |
default_timer = time.perf_counter |
| 64 |
|
| 65 |
_globals = globals |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
template = """ |
| 71 |
def inner(_it, _timer{init}): |
| 72 |
{setup} |
| 73 |
_t0 = _timer() |
| 74 |
for _i in _it: |
| 75 |
{stmt} |
| 76 |
pass |
| 77 |
_t1 = _timer() |
| 78 |
return _t1 - _t0 |
| 79 |
""" |
| 80 |
|
| 81 |
|
| 82 |
def reindent(src, indent): |
| 83 |
"""Helper to reindent a multi-line statement.""" |
| 84 |
return src.replace("\n", "\n" + " " * indent) |
| 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 |
|
| 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 |
|
| 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 |
| 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): |
| 141 |
"""Helper to print a traceback from the timed code. |
| 142 |
|
| 143 |
Typical use: |
| 144 |
|
| 145 |
t = Timer(...) # outside the try/except |
| 146 |
try: |
| 147 |
t.timeit(...) # or t.repeat(...) |
| 148 |
except: |
| 149 |
t.print_exc() |
| 150 |
|
| 151 |
The advantage over the standard traceback is that source lines |
| 152 |
in the compiled template will be displayed. |
| 153 |
|
| 154 |
The optional file argument directs where the traceback is |
| 155 |
sent; it defaults to sys.stderr. |
| 156 |
""" |
| 157 |
import linecache, traceback |
| 158 |
if self.src is not None: |
| 159 |
linecache.cache[dummy_src_name] = (len(self.src), |
| 160 |
None, |
| 161 |
self.src.split("\n"), |
| 162 |
dummy_src_name) |
| 163 |
|
| 164 |
|
| 165 |
traceback.print_exc(file=file) |
| 166 |
|
| 167 |
def timeit(self, number=default_number): |
| 168 |
"""Time 'number' executions of the main statement. |
| 169 |
|
| 170 |
To be precise, this executes the setup statement once, and |
| 171 |
then returns the time it takes to execute the main statement |
| 172 |
a number of times, as float seconds if using the default timer. The |
| 173 |
argument is the number of times through the loop, defaulting |
| 174 |
to one million. The main statement, the setup statement and |
| 175 |
the timer function to be used are passed to the constructor. |
| 176 |
""" |
| 177 |
it = itertools.repeat(None, number) |
| 178 |
gcold = gc.isenabled() |
| 179 |
if '__pypy__' not in sys.builtin_module_names: |
| 180 |
gc.disable() |
| 181 |
try: |
| 182 |
timing = self.inner(it, self.timer) |
| 183 |
finally: |
| 184 |
if gcold: |
| 185 |
gc.enable() |
| 186 |
return timing |
| 187 |
|
| 188 |
def repeat(self, repeat=default_repeat, number=default_number): |
| 189 |
"""Call timeit() a few times. |
| 190 |
|
| 191 |
This is a convenience function that calls the timeit() |
| 192 |
repeatedly, returning a list of results. The first argument |
| 193 |
specifies how many times to call timeit(), defaulting to 5; |
| 194 |
the second argument specifies the timer argument, defaulting |
| 195 |
to one million. |
| 196 |
|
| 197 |
Note: it's tempting to calculate mean and standard deviation |
| 198 |
from the result vector and report these. However, this is not |
| 199 |
very useful. In a typical case, the lowest value gives a |
| 200 |
lower bound for how fast your machine can run the given code |
| 201 |
snippet; higher values in the result vector are typically not |
| 202 |
caused by variability in Python's speed, but by other |
| 203 |
processes interfering with your timing accuracy. So the min() |
| 204 |
of the result is probably the only number you should be |
| 205 |
interested in. After that, you should look at the entire |
| 206 |
vector and apply common sense rather than statistics. |
| 207 |
""" |
| 208 |
r = [] |
| 209 |
for i in range(repeat): |
| 210 |
t = self.timeit(number) |
| 211 |
r.append(t) |
| 212 |
return r |
| 213 |
|
| 214 |
def autorange(self, callback=None): |
| 215 |
"""Return the number of loops and time taken so that total time >= 0.2. |
| 216 |
|
| 217 |
Calls the timeit method with increasing numbers from the sequence |
| 218 |
1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2 |
| 219 |
second. Returns (number, time_taken). |
| 220 |
|
| 221 |
If *callback* is given and is not None, it will be called after |
| 222 |
each trial with two arguments: ``callback(number, time_taken)``. |
| 223 |
""" |
| 224 |
i = 1 |
| 225 |
while True: |
| 226 |
for j in 1, 2, 5: |
| 227 |
number = i * j |
| 228 |
time_taken = self.timeit(number) |
| 229 |
if callback: |
| 230 |
callback(number, time_taken) |
| 231 |
if time_taken >= 0.2: |
| 232 |
return (number, time_taken) |
| 233 |
i *= 10 |
| 234 |
|
| 235 |
|
| 236 |
def timeit(stmt="pass", setup="pass", timer=default_timer, |
| 237 |
number=default_number, globals=None): |
| 238 |
"""Convenience function to create Timer object and call timeit method.""" |
| 239 |
return Timer(stmt, setup, timer, globals).timeit(number) |
| 240 |
|
| 241 |
|
| 242 |
def repeat(stmt="pass", setup="pass", timer=default_timer, |
| 243 |
repeat=default_repeat, number=default_number, globals=None): |
| 244 |
"""Convenience function to create Timer object and call repeat method.""" |
| 245 |
return Timer(stmt, setup, timer, globals).repeat(repeat, number) |
| 246 |
|
| 247 |
|
| 248 |
def main(args=None, *, _wrap_timer=None): |
| 249 |
"""Main program, used when run as a script. |
| 250 |
|
| 251 |
The optional 'args' argument specifies the command line to be parsed, |
| 252 |
defaulting to sys.argv[1:]. |
| 253 |
|
| 254 |
The return value is an exit code to be passed to sys.exit(); it |
| 255 |
may be None to indicate success. |
| 256 |
|
| 257 |
When an exception happens during timing, a traceback is printed to |
| 258 |
stderr and the return value is 1. Exceptions at other times |
| 259 |
(including the template compilation) are not caught. |
| 260 |
|
| 261 |
'_wrap_timer' is an internal interface used for unit testing. If it |
| 262 |
is not None, it must be a callable that accepts a timer function |
| 263 |
and returns another timer function (used for unit testing). |
| 264 |
""" |
| 265 |
if args is None: |
| 266 |
args = sys.argv[1:] |
| 267 |
origargs = args |
| 268 |
import getopt |
| 269 |
try: |
| 270 |
opts, args = getopt.getopt(args, "n:u:s:r:tcpvh", |
| 271 |
["number=", "setup=", "repeat=", |
| 272 |
"time", "clock", "process", |
| 273 |
"verbose", "unit=", "help"]) |
| 274 |
except getopt.error as err: |
| 275 |
print(err) |
| 276 |
print("use -h/--help for command line help") |
| 277 |
return 2 |
| 278 |
|
| 279 |
timer = default_timer |
| 280 |
stmt = "\n".join(args) or "pass" |
| 281 |
number = 0 |
| 282 |
setup = [] |
| 283 |
repeat = default_repeat |
| 284 |
verbose = 0 |
| 285 |
time_unit = None |
| 286 |
units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} |
| 287 |
precision = 3 |
| 288 |
for o, a in opts: |
| 289 |
if o in ("-n", "--number"): |
| 290 |
number = int(a) |
| 291 |
if o in ("-s", "--setup"): |
| 292 |
setup.append(a) |
| 293 |
if o in ("-u", "--unit"): |
| 294 |
if a in units: |
| 295 |
time_unit = a |
| 296 |
else: |
| 297 |
print("Unrecognized unit. Please select nsec, usec, msec, or sec.", |
| 298 |
file=sys.stderr) |
| 299 |
return 2 |
| 300 |
if o in ("-r", "--repeat"): |
| 301 |
repeat = int(a) |
| 302 |
if repeat <= 0: |
| 303 |
repeat = 1 |
| 304 |
if o in ("-p", "--process"): |
| 305 |
timer = time.process_time |
| 306 |
if o in ("-v", "--verbose"): |
| 307 |
if verbose: |
| 308 |
precision += 1 |
| 309 |
verbose += 1 |
| 310 |
if o in ("-h", "--help"): |
| 311 |
print(__doc__, end=' ') |
| 312 |
return 0 |
| 313 |
setup = "\n".join(setup) or "pass" |
| 314 |
|
| 315 |
import os |
| 316 |
print("WARNING: timeit is a very unreliable tool. use pyperf or something else for real measurements") |
| 317 |
executable = os.path.basename(sys.executable) |
| 318 |
print("%s -m pip install pyperf" % executable) |
| 319 |
print("%s -m pyperf timeit %s" % ( |
| 320 |
executable, |
| 321 |
" ".join([(arg if arg.startswith("-") else repr(arg)) |
| 322 |
for arg in origargs]), )) |
| 323 |
print("-" * 60) |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
sys.path.insert(0, os.curdir) |
| 328 |
if _wrap_timer is not None: |
| 329 |
timer = _wrap_timer(timer) |
| 330 |
|
| 331 |
t = Timer(stmt, setup, timer) |
| 332 |
if number == 0: |
| 333 |
|
| 334 |
callback = None |
| 335 |
if verbose: |
| 336 |
def callback(number, time_taken): |
| 337 |
msg = "{num} loop{s} -> {secs:.{prec}g} secs" |
| 338 |
plural = (number != 1) |
| 339 |
print(msg.format(num=number, s='s' if plural else '', |
| 340 |
secs=time_taken, prec=precision)) |
| 341 |
try: |
| 342 |
number, _ = t.autorange(callback) |
| 343 |
except: |
| 344 |
t.print_exc() |
| 345 |
return 1 |
| 346 |
|
| 347 |
if verbose: |
| 348 |
print() |
| 349 |
|
| 350 |
try: |
| 351 |
raw_timings = t.repeat(repeat, number) |
| 352 |
except: |
| 353 |
t.print_exc() |
| 354 |
return 1 |
| 355 |
|
| 356 |
def format_time(dt, stdev=None): |
| 357 |
unit = time_unit |
| 358 |
|
| 359 |
if unit is not None: |
| 360 |
scale = units[unit] |
| 361 |
else: |
| 362 |
scales = [(scale, unit) for unit, scale in units.items()] |
| 363 |
scales.sort(reverse=True) |
| 364 |
for scale, unit in scales: |
| 365 |
if dt >= scale: |
| 366 |
break |
| 367 |
|
| 368 |
if stdev is None: |
| 369 |
return "%.*g %s" % (precision, dt / scale, unit) |
| 370 |
else: |
| 371 |
return "%.*g +- %.*g %s" % (precision, dt / scale, |
| 372 |
precision, stdev / scale, unit) |
| 373 |
|
| 374 |
if verbose: |
| 375 |
print("raw times: %s" % ", ".join(map(format_time, raw_timings))) |
| 376 |
print() |
| 377 |
timings = [dt / number for dt in raw_timings] |
| 378 |
|
| 379 |
def _avg(l): |
| 380 |
return math.fsum(l) / len(l) |
| 381 |
def _stdev(l): |
| 382 |
avg = _avg(l) |
| 383 |
return (math.fsum([(x - avg) ** 2 for x in l]) / len(l)) ** 0.5 |
| 384 |
|
| 385 |
average = _avg(timings) |
| 386 |
stdev = _stdev(timings) |
| 387 |
|
| 388 |
print("%s loops, average of %d: %s per loop (using standard deviation)" |
| 389 |
% (number, repeat, format_time(average, stdev))) |
| 390 |
|
| 391 |
best = min(timings) |
| 392 |
worst = max(timings) |
| 393 |
if worst >= best * 4: |
| 394 |
import warnings |
| 395 |
warnings.warn_explicit("The test results are likely unreliable. " |
| 396 |
"The worst time (%s) was more than four times " |
| 397 |
"slower than the best time (%s)." |
| 398 |
% (format_time(worst), format_time(best)), |
| 399 |
UserWarning, '', 0) |
| 400 |
return None |
| 401 |
|
| 402 |
|
| 403 |
if __name__ == "__main__": |
| 404 |
sys.exit(main()) |