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