blob: 9dfd454936e6b8c790297f2020d1295fc447dde6 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Skip Montanarocfd55502003-04-08 19:49:40 +00002
Guido van Rossum6e31aad2003-03-07 01:33:18 +00003"""Tool for measuring execution time of small code snippets.
Guido van Rossumb3f09d42003-03-05 23:31:58 +00004
Guido van Rossumb7ab6002003-03-06 02:32:19 +00005This module avoids a number of common traps for measuring execution
6times. See also Tim Peters' introduction to the Algorithms chapter in
7the Python Cookbook, published by O'Reilly.
Guido van Rossumb3f09d42003-03-05 23:31:58 +00008
Guido van Rossumb7ab6002003-03-06 02:32:19 +00009Library usage: see the Timer class.
Guido van Rossumb3f09d42003-03-05 23:31:58 +000010
11Command line usage:
Victor Stinner3d7feb92016-10-18 17:18:21 +020012 python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement]
Guido van Rossumb3f09d42003-03-05 23:31:58 +000013
14Options:
Guido van Rossumb7ab6002003-03-06 02:32:19 +000015 -n/--number N: how many times to execute 'statement' (default: see below)
Victor Stinner3ef769f2018-06-06 17:55:18 +020016 -r/--repeat N: how many times to repeat the timer (default 5)
Andrew Kuchling333518e2015-04-21 19:43:33 -040017 -s/--setup S: statement to be executed once initially (default 'pass').
18 Execution time of this setup statement is NOT timed.
Georg Brandlc9d77b22012-05-01 11:56:22 +020019 -p/--process: use time.process_time() (default is time.perf_counter())
Guido van Rossum0070f002003-03-15 12:25:00 +000020 -v/--verbose: print raw timing results; repeat for more digits precision
Victor Stinnerc3e40f82016-10-18 17:42:48 +020021 -u/--unit: set the output time unit (nsec, usec, msec, or sec)
Guido van Rossume8577b72003-03-06 03:02:10 +000022 -h/--help: print this usage message and exit
Georg Brandl794f5b32010-08-01 08:52:32 +000023 --: separate options from statement, use when statement starts with -
Guido van Rossumb3f09d42003-03-05 23:31:58 +000024 statement: statement to be timed (default 'pass')
Guido van Rossumb7ab6002003-03-06 02:32:19 +000025
26A multi-line statement may be given by specifying each line as a
27separate argument; indented lines are possible by enclosing an
Guido van Rossum6e31aad2003-03-07 01:33:18 +000028argument in quotes and using leading spaces. Multiple -s options are
29treated similarly.
Guido van Rossumb7ab6002003-03-06 02:32:19 +000030
31If -n is not given, a suitable number of loops is calculated by trying
Sander76635232020-05-02 18:12:05 +020032increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the
33total time is at least 0.2 seconds.
Guido van Rossumb7ab6002003-03-06 02:32:19 +000034
Guido van Rossume8577b72003-03-06 03:02:10 +000035Note: there is a certain baseline overhead associated with executing a
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040036pass statement. It differs between versions. The code here doesn't try
37to hide it, but you should be aware of it. The baseline overhead can be
38measured by invoking the program without arguments.
Guido van Rossum6e31aad2003-03-07 01:33:18 +000039
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040040Classes:
41
42 Timer
43
44Functions:
45
46 timeit(string, string) -> float
47 repeat(string, string) -> list
48 default_timer() -> float
49
Guido van Rossumb3f09d42003-03-05 23:31:58 +000050"""
51
Raymond Hettinger816ed1b2004-01-04 03:47:51 +000052import gc
Guido van Rossumb3f09d42003-03-05 23:31:58 +000053import sys
Guido van Rossumb3f09d42003-03-05 23:31:58 +000054import time
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040055import itertools
Guido van Rossumb3f09d42003-03-05 23:31:58 +000056
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040057__all__ = ["Timer", "timeit", "repeat", "default_timer"]
Guido van Rossumb3f09d42003-03-05 23:31:58 +000058
Guido van Rossum538f1d82003-03-14 17:21:00 +000059dummy_src_name = "<timeit-src>"
Guido van Rossumb3f09d42003-03-05 23:31:58 +000060default_number = 1000000
Victor Stinner1b901152016-10-18 17:13:22 +020061default_repeat = 5
Victor Stinnerfe98e2f2012-04-29 03:01:20 +020062default_timer = time.perf_counter
Guido van Rossumb3f09d42003-03-05 23:31:58 +000063
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -040064_globals = globals
65
Guido van Rossumb7ab6002003-03-06 02:32:19 +000066# Don't change the indentation of the template; the reindent() calls
67# in Timer.__init__() depend on setup being indented 4 spaces and stmt
68# being indented 8 spaces.
Guido van Rossumb3f09d42003-03-05 23:31:58 +000069template = """
Serhiy Storchakaf28fa662015-05-30 19:38:26 +030070def inner(_it, _timer{init}):
Raymond Hettingerc800af42011-04-04 09:28:25 -070071 {setup}
Guido van Rossum538f1d82003-03-14 17:21:00 +000072 _t0 = _timer()
Guido van Rossumdd42edc2003-03-21 14:54:19 +000073 for _i in _it:
Raymond Hettingerc800af42011-04-04 09:28:25 -070074 {stmt}
Serhiy Storchaka557b9a52020-09-22 16:16:46 +030075 pass
Guido van Rossum538f1d82003-03-14 17:21:00 +000076 _t1 = _timer()
77 return _t1 - _t0
Guido van Rossumb3f09d42003-03-05 23:31:58 +000078"""
79
80def reindent(src, indent):
Guido van Rossumb7ab6002003-03-06 02:32:19 +000081 """Helper to reindent a multi-line statement."""
Guido van Rossume05dcce2003-03-06 13:09:09 +000082 return src.replace("\n", "\n" + " "*indent)
Guido van Rossumb3f09d42003-03-05 23:31:58 +000083
84class Timer:
Guido van Rossumb7ab6002003-03-06 02:32:19 +000085 """Class for timing execution speed of small code snippets.
86
87 The constructor takes a statement to be timed, an additional
88 statement used for setup, and a timer function. Both statements
89 default to 'pass'; the timer function is platform-dependent (see
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -040090 module doc string). If 'globals' is specified, the code will be
91 executed within that namespace (as opposed to inside timeit's
92 namespace).
Guido van Rossumb7ab6002003-03-06 02:32:19 +000093
94 To measure the execution time of the first statement, use the
95 timeit() method. The repeat() method is a convenience to call
96 timeit() multiple times and return a list of results.
97
98 The statements may contain newlines, as long as they don't contain
99 multi-line string literals.
100 """
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000101
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400102 def __init__(self, stmt="pass", setup="pass", timer=default_timer,
103 globals=None):
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000104 """Constructor. See class doc string."""
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000105 self.timer = timer
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400106 local_ns = {}
107 global_ns = _globals() if globals is None else globals
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300108 init = ''
109 if isinstance(setup, str):
110 # Check that the code can be compiled outside a function
111 compile(setup, dummy_src_name, "exec")
Serhiy Storchakaced770d2015-07-15 22:11:36 +0300112 stmtprefix = setup + '\n'
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300113 setup = reindent(setup, 4)
114 elif callable(setup):
115 local_ns['_setup'] = setup
116 init += ', _setup=_setup'
Serhiy Storchakaced770d2015-07-15 22:11:36 +0300117 stmtprefix = ''
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300118 setup = '_setup()'
119 else:
120 raise ValueError("setup is neither a string nor callable")
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000121 if isinstance(stmt, str):
Serhiy Storchaka2bef5852015-01-26 12:09:17 +0200122 # Check that the code can be compiled outside a function
Serhiy Storchakaced770d2015-07-15 22:11:36 +0300123 compile(stmtprefix + stmt, dummy_src_name, "exec")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 stmt = reindent(stmt, 8)
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200125 elif callable(stmt):
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300126 local_ns['_stmt'] = stmt
127 init += ', _stmt=_stmt'
128 stmt = '_stmt()'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129 else:
130 raise ValueError("stmt is neither a string nor callable")
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300131 src = template.format(stmt=stmt, setup=setup, init=init)
132 self.src = src # Save for traceback display
133 code = compile(src, dummy_src_name, "exec")
134 exec(code, global_ns, local_ns)
135 self.inner = local_ns["inner"]
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000136
Guido van Rossum538f1d82003-03-14 17:21:00 +0000137 def print_exc(self, file=None):
138 """Helper to print a traceback from the timed code.
139
140 Typical use:
141
142 t = Timer(...) # outside the try/except
143 try:
144 t.timeit(...) # or t.repeat(...)
145 except:
146 t.print_exc()
147
148 The advantage over the standard traceback is that source lines
149 in the compiled template will be displayed.
150
151 The optional file argument directs where the traceback is
152 sent; it defaults to sys.stderr.
153 """
154 import linecache, traceback
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155 if self.src is not None:
156 linecache.cache[dummy_src_name] = (len(self.src),
157 None,
158 self.src.split("\n"),
159 dummy_src_name)
160 # else the source is already stored somewhere else
161
Guido van Rossum538f1d82003-03-14 17:21:00 +0000162 traceback.print_exc(file=file)
163
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000164 def timeit(self, number=default_number):
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000165 """Time 'number' executions of the main statement.
166
167 To be precise, this executes the setup statement once, and
168 then returns the time it takes to execute the main statement
169 a number of times, as a float measured in seconds. The
170 argument is the number of times through the loop, defaulting
171 to one million. The main statement, the setup statement and
172 the timer function to be used are passed to the constructor.
173 """
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -0400174 it = itertools.repeat(None, number)
Raymond Hettinger816ed1b2004-01-04 03:47:51 +0000175 gcold = gc.isenabled()
176 gc.disable()
Raymond Hettinger3a081f52011-07-29 00:02:04 -0700177 try:
178 timing = self.inner(it, self.timer)
179 finally:
180 if gcold:
181 gc.enable()
Raymond Hettinger816ed1b2004-01-04 03:47:51 +0000182 return timing
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000183
184 def repeat(self, repeat=default_repeat, number=default_number):
Skip Montanarofb2a6cc2003-04-08 19:40:19 +0000185 """Call timeit() a few times.
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000186
Skip Montanarofb2a6cc2003-04-08 19:40:19 +0000187 This is a convenience function that calls the timeit()
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000188 repeatedly, returning a list of results. The first argument
Victor Stinner3ef769f2018-06-06 17:55:18 +0200189 specifies how many times to call timeit(), defaulting to 5;
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000190 the second argument specifies the timer argument, defaulting
191 to one million.
Guido van Rossum55735412003-03-06 16:11:17 +0000192
193 Note: it's tempting to calculate mean and standard deviation
194 from the result vector and report these. However, this is not
195 very useful. In a typical case, the lowest value gives a
196 lower bound for how fast your machine can run the given code
197 snippet; higher values in the result vector are typically not
198 caused by variability in Python's speed, but by other
199 processes interfering with your timing accuracy. So the min()
200 of the result is probably the only number you should be
201 interested in. After that, you should look at the entire
202 vector and apply common sense rather than statistics.
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000203 """
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000204 r = []
205 for i in range(repeat):
206 t = self.timeit(number)
207 r.append(t)
208 return r
209
Steven D'Aprano09f4f712016-08-15 01:27:03 +1000210 def autorange(self, callback=None):
Xiang Zhangecf39bb2017-02-28 11:06:07 +0800211 """Return the number of loops and time taken so that total time >= 0.2.
Steven D'Aprano09f4f712016-08-15 01:27:03 +1000212
Serhiy Storchakad3ff7842016-10-23 15:17:05 +0300213 Calls the timeit method with increasing numbers from the sequence
214 1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2
215 second. Returns (number, time_taken).
Steven D'Aprano09f4f712016-08-15 01:27:03 +1000216
217 If *callback* is given and is not None, it will be called after
218 each trial with two arguments: ``callback(number, time_taken)``.
219 """
Serhiy Storchakad3ff7842016-10-23 15:17:05 +0300220 i = 1
221 while True:
222 for j in 1, 2, 5:
223 number = i * j
224 time_taken = self.timeit(number)
225 if callback:
226 callback(number, time_taken)
227 if time_taken >= 0.2:
228 return (number, time_taken)
229 i *= 10
Steven D'Aprano09f4f712016-08-15 01:27:03 +1000230
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231def timeit(stmt="pass", setup="pass", timer=default_timer,
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400232 number=default_number, globals=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233 """Convenience function to create Timer object and call timeit method."""
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400234 return Timer(stmt, setup, timer, globals).timeit(number)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
236def repeat(stmt="pass", setup="pass", timer=default_timer,
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400237 repeat=default_repeat, number=default_number, globals=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238 """Convenience function to create Timer object and call repeat method."""
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400239 return Timer(stmt, setup, timer, globals).repeat(repeat, number)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
R David Murraya88da672011-03-16 17:32:27 -0400241def main(args=None, *, _wrap_timer=None):
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000242 """Main program, used when run as a script.
243
R David Murraya88da672011-03-16 17:32:27 -0400244 The optional 'args' argument specifies the command line to be parsed,
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000245 defaulting to sys.argv[1:].
246
247 The return value is an exit code to be passed to sys.exit(); it
248 may be None to indicate success.
Guido van Rossum538f1d82003-03-14 17:21:00 +0000249
250 When an exception happens during timing, a traceback is printed to
251 stderr and the return value is 1. Exceptions at other times
252 (including the template compilation) are not caught.
R David Murraya88da672011-03-16 17:32:27 -0400253
254 '_wrap_timer' is an internal interface used for unit testing. If it
255 is not None, it must be a callable that accepts a timer function
256 and returns another timer function (used for unit testing).
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000257 """
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000258 if args is None:
259 args = sys.argv[1:]
260 import getopt
261 try:
Robert Collins302dbc62015-03-18 09:54:50 +1300262 opts, args = getopt.getopt(args, "n:u:s:r:tcpvh",
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000263 ["number=", "setup=", "repeat=",
Georg Brandlc9d77b22012-05-01 11:56:22 +0200264 "time", "clock", "process",
Robert Collins302dbc62015-03-18 09:54:50 +1300265 "verbose", "unit=", "help"])
Guido van Rossumb940e112007-01-10 16:19:56 +0000266 except getopt.error as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000267 print(err)
268 print("use -h/--help for command line help")
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000269 return 2
Victor Stinner61de57f2016-10-18 17:56:42 +0200270
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000271 timer = default_timer
272 stmt = "\n".join(args) or "pass"
273 number = 0 # auto-determine
Guido van Rossum6e31aad2003-03-07 01:33:18 +0000274 setup = []
Guido van Rossum0070f002003-03-15 12:25:00 +0000275 repeat = default_repeat
276 verbose = 0
Robert Collins302dbc62015-03-18 09:54:50 +1300277 time_unit = None
Victor Stinnerc3e40f82016-10-18 17:42:48 +0200278 units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0}
Guido van Rossum0070f002003-03-15 12:25:00 +0000279 precision = 3
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000280 for o, a in opts:
281 if o in ("-n", "--number"):
282 number = int(a)
283 if o in ("-s", "--setup"):
Guido van Rossum6e31aad2003-03-07 01:33:18 +0000284 setup.append(a)
Robert Collins302dbc62015-03-18 09:54:50 +1300285 if o in ("-u", "--unit"):
286 if a in units:
287 time_unit = a
288 else:
Victor Stinnerc3e40f82016-10-18 17:42:48 +0200289 print("Unrecognized unit. Please select nsec, usec, msec, or sec.",
Robert Collins302dbc62015-03-18 09:54:50 +1300290 file=sys.stderr)
291 return 2
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000292 if o in ("-r", "--repeat"):
293 repeat = int(a)
294 if repeat <= 0:
295 repeat = 1
Georg Brandlc9d77b22012-05-01 11:56:22 +0200296 if o in ("-p", "--process"):
297 timer = time.process_time
Guido van Rossum0070f002003-03-15 12:25:00 +0000298 if o in ("-v", "--verbose"):
299 if verbose:
300 precision += 1
301 verbose += 1
Guido van Rossume8577b72003-03-06 03:02:10 +0000302 if o in ("-h", "--help"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000303 print(__doc__, end=' ')
Guido van Rossume8577b72003-03-06 03:02:10 +0000304 return 0
Guido van Rossum6e31aad2003-03-07 01:33:18 +0000305 setup = "\n".join(setup) or "pass"
Victor Stinner61de57f2016-10-18 17:56:42 +0200306
Raymond Hettinger22952a32003-05-20 04:59:56 +0000307 # Include the current directory, so that local imports work (sys.path
308 # contains the directory of this script, rather than the current
309 # directory)
310 import os
311 sys.path.insert(0, os.curdir)
R David Murraya88da672011-03-16 17:32:27 -0400312 if _wrap_timer is not None:
313 timer = _wrap_timer(timer)
Victor Stinner61de57f2016-10-18 17:56:42 +0200314
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000315 t = Timer(stmt, setup, timer)
316 if number == 0:
317 # determine number so that 0.2 <= total time < 2.0
Steven D'Aprano09f4f712016-08-15 01:27:03 +1000318 callback = None
319 if verbose:
320 def callback(number, time_taken):
Victor Stinnerf8fb82c2016-10-18 17:06:56 +0200321 msg = "{num} loop{s} -> {secs:.{prec}g} secs"
322 plural = (number != 1)
323 print(msg.format(num=number, s='s' if plural else '',
324 secs=time_taken, prec=precision))
Steven D'Aprano09f4f712016-08-15 01:27:03 +1000325 try:
326 number, _ = t.autorange(callback)
327 except:
328 t.print_exc()
329 return 1
Victor Stinner61de57f2016-10-18 17:56:42 +0200330
Victor Stinner62cca922016-10-18 17:55:18 +0200331 if verbose:
332 print()
333
Guido van Rossum538f1d82003-03-14 17:21:00 +0000334 try:
Victor Stinner61de57f2016-10-18 17:56:42 +0200335 raw_timings = t.repeat(repeat, number)
Guido van Rossum538f1d82003-03-14 17:21:00 +0000336 except:
337 t.print_exc()
338 return 1
Victor Stinner61de57f2016-10-18 17:56:42 +0200339
340 def format_time(dt):
341 unit = time_unit
342
343 if unit is not None:
344 scale = units[unit]
345 else:
346 scales = [(scale, unit) for unit, scale in units.items()]
347 scales.sort(reverse=True)
348 for scale, unit in scales:
349 if dt >= scale:
350 break
351
352 return "%.*g %s" % (precision, dt / scale, unit)
353
Guido van Rossum0070f002003-03-15 12:25:00 +0000354 if verbose:
Victor Stinner61de57f2016-10-18 17:56:42 +0200355 print("raw times: %s" % ", ".join(map(format_time, raw_timings)))
Victor Stinner62cca922016-10-18 17:55:18 +0200356 print()
Victor Stinner61de57f2016-10-18 17:56:42 +0200357 timings = [dt / number for dt in raw_timings]
358
359 best = min(timings)
360 print("%d loop%s, best of %d: %s per loop"
361 % (number, 's' if number != 1 else '',
362 repeat, format_time(best)))
363
364 best = min(timings)
365 worst = max(timings)
Robert Collins69de2a52015-08-26 12:40:28 +1200366 if worst >= best * 4:
Robert Collins69de2a52015-08-26 12:40:28 +1200367 import warnings
Victor Stinner61de57f2016-10-18 17:56:42 +0200368 warnings.warn_explicit("The test results are likely unreliable. "
369 "The worst time (%s) was more than four times "
370 "slower than the best time (%s)."
Victor Stinneraf48a912016-10-19 15:48:23 +0200371 % (format_time(worst), format_time(best)),
Victor Stinner61de57f2016-10-18 17:56:42 +0200372 UserWarning, '', 0)
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000373 return None
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000374
375if __name__ == "__main__":
376 sys.exit(main())