blob: d9f9563c2e646eb59acbc6f0c71946c12f5fb4a7 [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:
Georg Brandlc9d77b22012-05-01 11:56:22 +020012 python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-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)
Guido van Rossum0070f002003-03-15 12:25:00 +000016 -r/--repeat N: how many times to repeat the timer (default 3)
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())
20 -t/--time: use time.time() (deprecated)
21 -c/--clock: use time.clock() (deprecated)
Guido van Rossum0070f002003-03-15 12:25:00 +000022 -v/--verbose: print raw timing results; repeat for more digits precision
Robert Collins302dbc62015-03-18 09:54:50 +130023 -u/--unit: set the output time unit (usec, msec, or sec)
Guido van Rossume8577b72003-03-06 03:02:10 +000024 -h/--help: print this usage message and exit
Georg Brandl794f5b32010-08-01 08:52:32 +000025 --: separate options from statement, use when statement starts with -
Guido van Rossumb3f09d42003-03-05 23:31:58 +000026 statement: statement to be timed (default 'pass')
Guido van Rossumb7ab6002003-03-06 02:32:19 +000027
28A multi-line statement may be given by specifying each line as a
29separate argument; indented lines are possible by enclosing an
Guido van Rossum6e31aad2003-03-07 01:33:18 +000030argument in quotes and using leading spaces. Multiple -s options are
31treated similarly.
Guido van Rossumb7ab6002003-03-06 02:32:19 +000032
33If -n is not given, a suitable number of loops is calculated by trying
34successive powers of 10 until the total time is at least 0.2 seconds.
35
Guido van Rossume8577b72003-03-06 03:02:10 +000036Note: there is a certain baseline overhead associated with executing a
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040037pass statement. It differs between versions. The code here doesn't try
38to hide it, but you should be aware of it. The baseline overhead can be
39measured by invoking the program without arguments.
Guido van Rossum6e31aad2003-03-07 01:33:18 +000040
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040041Classes:
42
43 Timer
44
45Functions:
46
47 timeit(string, string) -> float
48 repeat(string, string) -> list
49 default_timer() -> float
50
Guido van Rossumb3f09d42003-03-05 23:31:58 +000051"""
52
Raymond Hettinger816ed1b2004-01-04 03:47:51 +000053import gc
Guido van Rossumb3f09d42003-03-05 23:31:58 +000054import sys
Guido van Rossumb3f09d42003-03-05 23:31:58 +000055import time
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040056import itertools
Guido van Rossumb3f09d42003-03-05 23:31:58 +000057
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -040058__all__ = ["Timer", "timeit", "repeat", "default_timer"]
Guido van Rossumb3f09d42003-03-05 23:31:58 +000059
Guido van Rossum538f1d82003-03-14 17:21:00 +000060dummy_src_name = "<timeit-src>"
Guido van Rossumb3f09d42003-03-05 23:31:58 +000061default_number = 1000000
Guido van Rossum0070f002003-03-15 12:25:00 +000062default_repeat = 3
Victor Stinnerfe98e2f2012-04-29 03:01:20 +020063default_timer = time.perf_counter
Guido van Rossumb3f09d42003-03-05 23:31:58 +000064
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -040065_globals = globals
66
Guido van Rossumb7ab6002003-03-06 02:32:19 +000067# Don't change the indentation of the template; the reindent() calls
68# in Timer.__init__() depend on setup being indented 4 spaces and stmt
69# being indented 8 spaces.
Guido van Rossumb3f09d42003-03-05 23:31:58 +000070template = """
Serhiy Storchakaf28fa662015-05-30 19:38:26 +030071def inner(_it, _timer{init}):
Raymond Hettingerc800af42011-04-04 09:28:25 -070072 {setup}
Guido van Rossum538f1d82003-03-14 17:21:00 +000073 _t0 = _timer()
Guido van Rossumdd42edc2003-03-21 14:54:19 +000074 for _i in _it:
Raymond Hettingerc800af42011-04-04 09:28:25 -070075 {stmt}
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")
112 setup = reindent(setup, 4)
113 elif callable(setup):
114 local_ns['_setup'] = setup
115 init += ', _setup=_setup'
116 setup = '_setup()'
117 else:
118 raise ValueError("setup is neither a string nor callable")
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000119 if isinstance(stmt, str):
Serhiy Storchaka2bef5852015-01-26 12:09:17 +0200120 # Check that the code can be compiled outside a function
121 if isinstance(setup, str):
Serhiy Storchaka2bef5852015-01-26 12:09:17 +0200122 compile(setup + '\n' + stmt, dummy_src_name, "exec")
123 else:
124 compile(stmt, dummy_src_name, "exec")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125 stmt = reindent(stmt, 8)
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200126 elif callable(stmt):
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300127 local_ns['_stmt'] = stmt
128 init += ', _stmt=_stmt'
129 stmt = '_stmt()'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130 else:
131 raise ValueError("stmt is neither a string nor callable")
Serhiy Storchaka1b560cb2015-05-30 19:44:55 +0300132 src = template.format(stmt=stmt, setup=setup, init=init)
133 self.src = src # Save for traceback display
134 code = compile(src, dummy_src_name, "exec")
135 exec(code, global_ns, local_ns)
136 self.inner = local_ns["inner"]
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000137
Guido van Rossum538f1d82003-03-14 17:21:00 +0000138 def print_exc(self, file=None):
139 """Helper to print a traceback from the timed code.
140
141 Typical use:
142
143 t = Timer(...) # outside the try/except
144 try:
145 t.timeit(...) # or t.repeat(...)
146 except:
147 t.print_exc()
148
149 The advantage over the standard traceback is that source lines
150 in the compiled template will be displayed.
151
152 The optional file argument directs where the traceback is
153 sent; it defaults to sys.stderr.
154 """
155 import linecache, traceback
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156 if self.src is not None:
157 linecache.cache[dummy_src_name] = (len(self.src),
158 None,
159 self.src.split("\n"),
160 dummy_src_name)
161 # else the source is already stored somewhere else
162
Guido van Rossum538f1d82003-03-14 17:21:00 +0000163 traceback.print_exc(file=file)
164
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000165 def timeit(self, number=default_number):
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000166 """Time 'number' executions of the main statement.
167
168 To be precise, this executes the setup statement once, and
169 then returns the time it takes to execute the main statement
170 a number of times, as a float measured in seconds. The
171 argument is the number of times through the loop, defaulting
172 to one million. The main statement, the setup statement and
173 the timer function to be used are passed to the constructor.
174 """
Terry Jan Reedyd49af5d2013-03-15 03:04:25 -0400175 it = itertools.repeat(None, number)
Raymond Hettinger816ed1b2004-01-04 03:47:51 +0000176 gcold = gc.isenabled()
177 gc.disable()
Raymond Hettinger3a081f52011-07-29 00:02:04 -0700178 try:
179 timing = self.inner(it, self.timer)
180 finally:
181 if gcold:
182 gc.enable()
Raymond Hettinger816ed1b2004-01-04 03:47:51 +0000183 return timing
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000184
185 def repeat(self, repeat=default_repeat, number=default_number):
Skip Montanarofb2a6cc2003-04-08 19:40:19 +0000186 """Call timeit() a few times.
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000187
Skip Montanarofb2a6cc2003-04-08 19:40:19 +0000188 This is a convenience function that calls the timeit()
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000189 repeatedly, returning a list of results. The first argument
Skip Montanarofb2a6cc2003-04-08 19:40:19 +0000190 specifies how many times to call timeit(), defaulting to 3;
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000191 the second argument specifies the timer argument, defaulting
192 to one million.
Guido van Rossum55735412003-03-06 16:11:17 +0000193
194 Note: it's tempting to calculate mean and standard deviation
195 from the result vector and report these. However, this is not
196 very useful. In a typical case, the lowest value gives a
197 lower bound for how fast your machine can run the given code
198 snippet; higher values in the result vector are typically not
199 caused by variability in Python's speed, but by other
200 processes interfering with your timing accuracy. So the min()
201 of the result is probably the only number you should be
202 interested in. After that, you should look at the entire
203 vector and apply common sense rather than statistics.
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000204 """
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000205 r = []
206 for i in range(repeat):
207 t = self.timeit(number)
208 r.append(t)
209 return r
210
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211def timeit(stmt="pass", setup="pass", timer=default_timer,
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400212 number=default_number, globals=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213 """Convenience function to create Timer object and call timeit method."""
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400214 return Timer(stmt, setup, timer, globals).timeit(number)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215
216def repeat(stmt="pass", setup="pass", timer=default_timer,
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400217 repeat=default_repeat, number=default_number, globals=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218 """Convenience function to create Timer object and call repeat method."""
Antoine Pitrouef3b9ed2014-08-22 23:13:50 -0400219 return Timer(stmt, setup, timer, globals).repeat(repeat, number)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220
R David Murraya88da672011-03-16 17:32:27 -0400221def main(args=None, *, _wrap_timer=None):
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000222 """Main program, used when run as a script.
223
R David Murraya88da672011-03-16 17:32:27 -0400224 The optional 'args' argument specifies the command line to be parsed,
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000225 defaulting to sys.argv[1:].
226
227 The return value is an exit code to be passed to sys.exit(); it
228 may be None to indicate success.
Guido van Rossum538f1d82003-03-14 17:21:00 +0000229
230 When an exception happens during timing, a traceback is printed to
231 stderr and the return value is 1. Exceptions at other times
232 (including the template compilation) are not caught.
R David Murraya88da672011-03-16 17:32:27 -0400233
234 '_wrap_timer' is an internal interface used for unit testing. If it
235 is not None, it must be a callable that accepts a timer function
236 and returns another timer function (used for unit testing).
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000237 """
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000238 if args is None:
239 args = sys.argv[1:]
240 import getopt
241 try:
Robert Collins302dbc62015-03-18 09:54:50 +1300242 opts, args = getopt.getopt(args, "n:u:s:r:tcpvh",
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000243 ["number=", "setup=", "repeat=",
Georg Brandlc9d77b22012-05-01 11:56:22 +0200244 "time", "clock", "process",
Robert Collins302dbc62015-03-18 09:54:50 +1300245 "verbose", "unit=", "help"])
Guido van Rossumb940e112007-01-10 16:19:56 +0000246 except getopt.error as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(err)
248 print("use -h/--help for command line help")
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000249 return 2
250 timer = default_timer
251 stmt = "\n".join(args) or "pass"
252 number = 0 # auto-determine
Guido van Rossum6e31aad2003-03-07 01:33:18 +0000253 setup = []
Guido van Rossum0070f002003-03-15 12:25:00 +0000254 repeat = default_repeat
255 verbose = 0
Robert Collins302dbc62015-03-18 09:54:50 +1300256 time_unit = None
257 units = {"usec": 1, "msec": 1e3, "sec": 1e6}
Guido van Rossum0070f002003-03-15 12:25:00 +0000258 precision = 3
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000259 for o, a in opts:
260 if o in ("-n", "--number"):
261 number = int(a)
262 if o in ("-s", "--setup"):
Guido van Rossum6e31aad2003-03-07 01:33:18 +0000263 setup.append(a)
Robert Collins302dbc62015-03-18 09:54:50 +1300264 if o in ("-u", "--unit"):
265 if a in units:
266 time_unit = a
267 else:
268 print("Unrecognized unit. Please select usec, msec, or sec.",
269 file=sys.stderr)
270 return 2
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000271 if o in ("-r", "--repeat"):
272 repeat = int(a)
273 if repeat <= 0:
274 repeat = 1
Guido van Rossume8577b72003-03-06 03:02:10 +0000275 if o in ("-t", "--time"):
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000276 timer = time.time
Guido van Rossume8577b72003-03-06 03:02:10 +0000277 if o in ("-c", "--clock"):
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000278 timer = time.clock
Georg Brandlc9d77b22012-05-01 11:56:22 +0200279 if o in ("-p", "--process"):
280 timer = time.process_time
Guido van Rossum0070f002003-03-15 12:25:00 +0000281 if o in ("-v", "--verbose"):
282 if verbose:
283 precision += 1
284 verbose += 1
Guido van Rossume8577b72003-03-06 03:02:10 +0000285 if o in ("-h", "--help"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000286 print(__doc__, end=' ')
Guido van Rossume8577b72003-03-06 03:02:10 +0000287 return 0
Guido van Rossum6e31aad2003-03-07 01:33:18 +0000288 setup = "\n".join(setup) or "pass"
Raymond Hettinger22952a32003-05-20 04:59:56 +0000289 # Include the current directory, so that local imports work (sys.path
290 # contains the directory of this script, rather than the current
291 # directory)
292 import os
293 sys.path.insert(0, os.curdir)
R David Murraya88da672011-03-16 17:32:27 -0400294 if _wrap_timer is not None:
295 timer = _wrap_timer(timer)
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000296 t = Timer(stmt, setup, timer)
297 if number == 0:
298 # determine number so that 0.2 <= total time < 2.0
299 for i in range(1, 10):
300 number = 10**i
Guido van Rossum538f1d82003-03-14 17:21:00 +0000301 try:
302 x = t.timeit(number)
303 except:
304 t.print_exc()
305 return 1
Guido van Rossum0070f002003-03-15 12:25:00 +0000306 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000307 print("%d loops -> %.*g secs" % (number, precision, x))
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000308 if x >= 0.2:
309 break
Guido van Rossum538f1d82003-03-14 17:21:00 +0000310 try:
311 r = t.repeat(repeat, number)
312 except:
313 t.print_exc()
314 return 1
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000315 best = min(r)
Guido van Rossum0070f002003-03-15 12:25:00 +0000316 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000317 print("raw times:", " ".join(["%.*g" % (precision, x) for x in r]))
318 print("%d loops," % number, end=' ')
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000319 usec = best * 1e6 / number
Robert Collins302dbc62015-03-18 09:54:50 +1300320 if time_unit is not None:
321 print("best of %d: %.*g %s per loop" % (repeat, precision,
322 usec/units[time_unit], time_unit))
Guido van Rossum57172082003-10-20 23:38:28 +0000323 else:
Robert Collins302dbc62015-03-18 09:54:50 +1300324 if usec < 1000:
325 print("best of %d: %.*g usec per loop" % (repeat, precision, usec))
Guido van Rossum57172082003-10-20 23:38:28 +0000326 else:
Robert Collins302dbc62015-03-18 09:54:50 +1300327 msec = usec / 1000
328 if msec < 1000:
329 print("best of %d: %.*g msec per loop" % (repeat,
330 precision, msec))
331 else:
332 sec = msec / 1000
333 print("best of %d: %.*g sec per loop" % (repeat,
334 precision, sec))
Guido van Rossumb7ab6002003-03-06 02:32:19 +0000335 return None
Guido van Rossumb3f09d42003-03-05 23:31:58 +0000336
337if __name__ == "__main__":
338 sys.exit(main())