1:mod:`timeit` --- Measure execution time of small code snippets 2=============================================================== 3 4.. module:: timeit 5 :synopsis: Measure the execution time of small code snippets. 6 7**Source code:** :source:`Lib/timeit.py` 8 9.. index:: 10 single: Benchmarking 11 single: Performance 12 13-------------- 14 15This module provides a simple way to time small bits of Python code. It has both 16a :ref:`timeit-command-line-interface` as well as a :ref:`callable <python-interface>` 17one. It avoids a number of common traps for measuring execution times. 18See also Tim Peters' introduction to the "Algorithms" chapter in the second 19edition of *Python Cookbook*, published by O'Reilly. 20 21 22Basic Examples 23-------------- 24 25The following example shows how the :ref:`timeit-command-line-interface` 26can be used to compare three different expressions: 27 28.. code-block:: shell-session 29 30 $ python3 -m timeit '"-".join(str(n) for n in range(100))' 31 10000 loops, best of 5: 30.2 usec per loop 32 $ python3 -m timeit '"-".join([str(n) for n in range(100)])' 33 10000 loops, best of 5: 27.5 usec per loop 34 $ python3 -m timeit '"-".join(map(str, range(100)))' 35 10000 loops, best of 5: 23.2 usec per loop 36 37This can be achieved from the :ref:`python-interface` with:: 38 39 >>> import timeit 40 >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 41 0.3018611848820001 42 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 43 0.2727368790656328 44 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 45 0.23702679807320237 46 47A callable can also be passed from the :ref:`python-interface`:: 48 49 >>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000) 50 0.19665591977536678 51 52Note however that :func:`.timeit` will automatically determine the number of 53repetitions only when the command-line interface is used. In the 54:ref:`timeit-examples` section you can find more advanced examples. 55 56 57.. _python-interface: 58 59Python Interface 60---------------- 61 62The module defines three convenience functions and a public class: 63 64 65.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None) 66 67 Create a :class:`Timer` instance with the given statement, *setup* code and 68 *timer* function and run its :meth:`.timeit` method with *number* executions. 69 The optional *globals* argument specifies a namespace in which to execute the 70 code. 71 72 .. versionchanged:: 3.5 73 The optional *globals* parameter was added. 74 75 76.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=5, number=1000000, globals=None) 77 78 Create a :class:`Timer` instance with the given statement, *setup* code and 79 *timer* function and run its :meth:`.repeat` method with the given *repeat* 80 count and *number* executions. The optional *globals* argument specifies a 81 namespace in which to execute the code. 82 83 .. versionchanged:: 3.5 84 The optional *globals* parameter was added. 85 86 .. versionchanged:: 3.7 87 Default value of *repeat* changed from 3 to 5. 88 89.. function:: default_timer() 90 91 The default timer, which is always :func:`time.perf_counter`. 92 93 .. versionchanged:: 3.3 94 :func:`time.perf_counter` is now the default timer. 95 96 97.. class:: Timer(stmt='pass', setup='pass', timer=<timer function>, globals=None) 98 99 Class for timing execution speed of small code snippets. 100 101 The constructor takes a statement to be timed, an additional statement used 102 for setup, and a timer function. Both statements default to ``'pass'``; 103 the timer function is platform-dependent (see the module doc string). 104 *stmt* and *setup* may also contain multiple statements separated by ``;`` 105 or newlines, as long as they don't contain multi-line string literals. The 106 statement will by default be executed within timeit's namespace; this behavior 107 can be controlled by passing a namespace to *globals*. 108 109 To measure the execution time of the first statement, use the :meth:`.timeit` 110 method. The :meth:`.repeat` and :meth:`.autorange` methods are convenience 111 methods to call :meth:`.timeit` multiple times. 112 113 The execution time of *setup* is excluded from the overall timed execution run. 114 115 The *stmt* and *setup* parameters can also take objects that are callable 116 without arguments. This will embed calls to them in a timer function that 117 will then be executed by :meth:`.timeit`. Note that the timing overhead is a 118 little larger in this case because of the extra function calls. 119 120 .. versionchanged:: 3.5 121 The optional *globals* parameter was added. 122 123 .. method:: Timer.timeit(number=1000000) 124 125 Time *number* executions of the main statement. This executes the setup 126 statement once, and then returns the time it takes to execute the main 127 statement a number of times, measured in seconds as a float. 128 The argument is the number of times through the loop, defaulting to one 129 million. The main statement, the setup statement and the timer function 130 to be used are passed to the constructor. 131 132 .. note:: 133 134 By default, :meth:`.timeit` temporarily turns off :term:`garbage 135 collection` during the timing. The advantage of this approach is that 136 it makes independent timings more comparable. The disadvantage is 137 that GC may be an important component of the performance of the 138 function being measured. If so, GC can be re-enabled as the first 139 statement in the *setup* string. For example:: 140 141 timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() 142 143 144 .. method:: Timer.autorange(callback=None) 145 146 Automatically determine how many times to call :meth:`.timeit`. 147 148 This is a convenience function that calls :meth:`.timeit` repeatedly 149 so that the total time >= 0.2 second, returning the eventual 150 (number of loops, time taken for that number of loops). It calls 151 :meth:`.timeit` with increasing numbers from the sequence 1, 2, 5, 152 10, 20, 50, ... until the time taken is at least 0.2 second. 153 154 If *callback* is given and is not ``None``, it will be called after 155 each trial with two arguments: ``callback(number, time_taken)``. 156 157 .. versionadded:: 3.6 158 159 160 .. method:: Timer.repeat(repeat=5, number=1000000) 161 162 Call :meth:`.timeit` a few times. 163 164 This is a convenience function that calls the :meth:`.timeit` repeatedly, 165 returning a list of results. The first argument specifies how many times 166 to call :meth:`.timeit`. The second argument specifies the *number* 167 argument for :meth:`.timeit`. 168 169 .. note:: 170 171 It's tempting to calculate mean and standard deviation from the result 172 vector and report these. However, this is not very useful. 173 In a typical case, the lowest value gives a lower bound for how fast 174 your machine can run the given code snippet; higher values in the 175 result vector are typically not caused by variability in Python's 176 speed, but by other processes interfering with your timing accuracy. 177 So the :func:`min` of the result is probably the only number you 178 should be interested in. After that, you should look at the entire 179 vector and apply common sense rather than statistics. 180 181 .. versionchanged:: 3.7 182 Default value of *repeat* changed from 3 to 5. 183 184 185 .. method:: Timer.print_exc(file=None) 186 187 Helper to print a traceback from the timed code. 188 189 Typical use:: 190 191 t = Timer(...) # outside the try/except 192 try: 193 t.timeit(...) # or t.repeat(...) 194 except Exception: 195 t.print_exc() 196 197 The advantage over the standard traceback is that source lines in the 198 compiled template will be displayed. The optional *file* argument directs 199 where the traceback is sent; it defaults to :data:`sys.stderr`. 200 201 202.. _timeit-command-line-interface: 203 204Command-Line Interface 205---------------------- 206 207When called as a program from the command line, the following form is used:: 208 209 python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...] 210 211Where the following options are understood: 212 213.. program:: timeit 214 215.. cmdoption:: -n N, --number=N 216 217 how many times to execute 'statement' 218 219.. cmdoption:: -r N, --repeat=N 220 221 how many times to repeat the timer (default 5) 222 223.. cmdoption:: -s S, --setup=S 224 225 statement to be executed once initially (default ``pass``) 226 227.. cmdoption:: -p, --process 228 229 measure process time, not wallclock time, using :func:`time.process_time` 230 instead of :func:`time.perf_counter`, which is the default 231 232 .. versionadded:: 3.3 233 234.. cmdoption:: -u, --unit=U 235 236 specify a time unit for timer output; can select ``nsec``, ``usec``, ``msec``, or ``sec`` 237 238 .. versionadded:: 3.5 239 240.. cmdoption:: -v, --verbose 241 242 print raw timing results; repeat for more digits precision 243 244.. cmdoption:: -h, --help 245 246 print a short usage message and exit 247 248A multi-line statement may be given by specifying each line as a separate 249statement argument; indented lines are possible by enclosing an argument in 250quotes and using leading spaces. Multiple :option:`-s` options are treated 251similarly. 252 253If :option:`-n` is not given, a suitable number of loops is calculated by trying 254increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the total 255time is at least 0.2 seconds. 256 257:func:`default_timer` measurements can be affected by other programs running on 258the same machine, so the best thing to do when accurate timing is necessary is 259to repeat the timing a few times and use the best time. The :option:`-r` 260option is good for this; the default of 5 repetitions is probably enough in 261most cases. You can use :func:`time.process_time` to measure CPU time. 262 263.. note:: 264 265 There is a certain baseline overhead associated with executing a pass statement. 266 The code here doesn't try to hide it, but you should be aware of it. The 267 baseline overhead can be measured by invoking the program without arguments, 268 and it might differ between Python versions. 269 270 271.. _timeit-examples: 272 273Examples 274-------- 275 276It is possible to provide a setup statement that is executed only once at the beginning: 277 278.. code-block:: shell-session 279 280 $ python -m timeit -s 'text = "sample string"; char = "g"' 'char in text' 281 5000000 loops, best of 5: 0.0877 usec per loop 282 $ python -m timeit -s 'text = "sample string"; char = "g"' 'text.find(char)' 283 1000000 loops, best of 5: 0.342 usec per loop 284 285In the output, there are three fields. The loop count, which tells you how many 286times the statement body was run per timing loop repetition. The repetition 287count ('best of 5') which tells you how many times the timing loop was 288repeated, and finally the time the statement body took on average within the 289best repetition of the timing loop. That is, the time the fastest repetition 290took divided by the loop count. 291 292:: 293 294 >>> import timeit 295 >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"') 296 0.41440500499993504 297 >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"') 298 1.7246671520006203 299 300The same can be done using the :class:`Timer` class and its methods:: 301 302 >>> import timeit 303 >>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"') 304 >>> t.timeit() 305 0.3955516149999312 306 >>> t.repeat() 307 [0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886] 308 309 310The following examples show how to time expressions that contain multiple lines. 311Here we compare the cost of using :func:`hasattr` vs. :keyword:`try`/:keyword:`except` 312to test for missing and present object attributes: 313 314.. code-block:: shell-session 315 316 $ python -m timeit 'try:' ' str.__bool__' 'except AttributeError:' ' pass' 317 20000 loops, best of 5: 15.7 usec per loop 318 $ python -m timeit 'if hasattr(str, "__bool__"): pass' 319 50000 loops, best of 5: 4.26 usec per loop 320 321 $ python -m timeit 'try:' ' int.__bool__' 'except AttributeError:' ' pass' 322 200000 loops, best of 5: 1.43 usec per loop 323 $ python -m timeit 'if hasattr(int, "__bool__"): pass' 324 100000 loops, best of 5: 2.23 usec per loop 325 326:: 327 328 >>> import timeit 329 >>> # attribute is missing 330 >>> s = """\ 331 ... try: 332 ... str.__bool__ 333 ... except AttributeError: 334 ... pass 335 ... """ 336 >>> timeit.timeit(stmt=s, number=100000) 337 0.9138244460009446 338 >>> s = "if hasattr(str, '__bool__'): pass" 339 >>> timeit.timeit(stmt=s, number=100000) 340 0.5829014980008651 341 >>> 342 >>> # attribute is present 343 >>> s = """\ 344 ... try: 345 ... int.__bool__ 346 ... except AttributeError: 347 ... pass 348 ... """ 349 >>> timeit.timeit(stmt=s, number=100000) 350 0.04215312199994514 351 >>> s = "if hasattr(int, '__bool__'): pass" 352 >>> timeit.timeit(stmt=s, number=100000) 353 0.08588060699912603 354 355 356To give the :mod:`timeit` module access to functions you define, you can pass a 357*setup* parameter which contains an import statement:: 358 359 def test(): 360 """Stupid test function""" 361 L = [i for i in range(100)] 362 363 if __name__ == '__main__': 364 import timeit 365 print(timeit.timeit("test()", setup="from __main__ import test")) 366 367Another option is to pass :func:`globals` to the *globals* parameter, which will cause the code 368to be executed within your current global namespace. This can be more convenient 369than individually specifying imports:: 370 371 def f(x): 372 return x**2 373 def g(x): 374 return x**4 375 def h(x): 376 return x**8 377 378 import timeit 379 print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals())) 380