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