| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 8 | .. index:: | 
 | 9 |    single: Benchmarking | 
 | 10 |    single: Performance | 
 | 11 |  | 
 | 12 | This module provides a simple way to time small bits of Python code. It has both | 
 | 13 | command line as well as callable interfaces.  It avoids a number of common traps | 
 | 14 | for measuring execution times.  See also Tim Peters' introduction to the | 
 | 15 | "Algorithms" chapter in the Python Cookbook, published by O'Reilly. | 
 | 16 |  | 
 | 17 | The module defines the following public class: | 
 | 18 |  | 
 | 19 |  | 
| Georg Brandl | b044b2a | 2009-09-16 16:05:59 +0000 | [diff] [blame] | 20 | .. class:: Timer(stmt='pass', setup='pass', timer=<timer function>) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 |  | 
 | 22 |    Class for timing execution speed of small code snippets. | 
 | 23 |  | 
 | 24 |    The constructor takes a statement to be timed, an additional statement used for | 
 | 25 |    setup, and a timer function.  Both statements default to ``'pass'``; the timer | 
| Benjamin Peterson | d76c8da | 2009-06-28 17:35:48 +0000 | [diff] [blame] | 26 |    function is platform-dependent (see the module doc string).  *stmt* and *setup* | 
 | 27 |    may also contain multiple statements separated by ``;`` or newlines, as long as | 
 | 28 |    they don't contain multi-line string literals. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 29 |  | 
 | 30 |    To measure the execution time of the first statement, use the :meth:`timeit` | 
 | 31 |    method.  The :meth:`repeat` method is a convenience to call :meth:`timeit` | 
 | 32 |    multiple times and return a list of results. | 
 | 33 |  | 
| Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 34 |    The *stmt* and *setup* parameters can also take objects that are callable | 
 | 35 |    without arguments. This will embed calls to them in a timer function that | 
 | 36 |    will then be executed by :meth:`timeit`.  Note that the timing overhead is a | 
 | 37 |    little larger in this case because of the extra function calls. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 |  | 
 | 39 |  | 
| Georg Brandl | b044b2a | 2009-09-16 16:05:59 +0000 | [diff] [blame] | 40 | .. method:: Timer.print_exc(file=None) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 41 |  | 
 | 42 |    Helper to print a traceback from the timed code. | 
 | 43 |  | 
 | 44 |    Typical use:: | 
 | 45 |  | 
 | 46 |       t = Timer(...)       # outside the try/except | 
 | 47 |       try: | 
 | 48 |           t.timeit(...)    # or t.repeat(...) | 
 | 49 |       except: | 
 | 50 |           t.print_exc() | 
 | 51 |  | 
 | 52 |    The advantage over the standard traceback is that source lines in the compiled | 
 | 53 |    template will be displayed. The optional *file* argument directs where the | 
 | 54 |    traceback is sent; it defaults to ``sys.stderr``. | 
 | 55 |  | 
 | 56 |  | 
| Georg Brandl | b044b2a | 2009-09-16 16:05:59 +0000 | [diff] [blame] | 57 | .. method:: Timer.repeat(repeat=3, number=1000000) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 58 |  | 
 | 59 |    Call :meth:`timeit` a few times. | 
 | 60 |  | 
 | 61 |    This is a convenience function that calls the :meth:`timeit` repeatedly, | 
 | 62 |    returning a list of results.  The first argument specifies how many times to | 
 | 63 |    call :meth:`timeit`.  The second argument specifies the *number* argument for | 
 | 64 |    :func:`timeit`. | 
 | 65 |  | 
 | 66 |    .. note:: | 
 | 67 |  | 
 | 68 |       It's tempting to calculate mean and standard deviation from the result vector | 
 | 69 |       and report these.  However, this is not very useful.  In a typical case, the | 
 | 70 |       lowest value gives a lower bound for how fast your machine can run the given | 
 | 71 |       code snippet; higher values in the result vector are typically not caused by | 
 | 72 |       variability in Python's speed, but by other processes interfering with your | 
 | 73 |       timing accuracy.  So the :func:`min` of the result is probably the only number | 
 | 74 |       you should be interested in.  After that, you should look at the entire vector | 
 | 75 |       and apply common sense rather than statistics. | 
 | 76 |  | 
 | 77 |  | 
| Georg Brandl | b044b2a | 2009-09-16 16:05:59 +0000 | [diff] [blame] | 78 | .. method:: Timer.timeit(number=1000000) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 79 |  | 
 | 80 |    Time *number* executions of the main statement. This executes the setup | 
 | 81 |    statement once, and then returns the time it takes to execute the main statement | 
 | 82 |    a number of times, measured in seconds as a float.  The argument is the number | 
 | 83 |    of times through the loop, defaulting to one million.  The main statement, the | 
 | 84 |    setup statement and the timer function to be used are passed to the constructor. | 
 | 85 |  | 
 | 86 |    .. note:: | 
 | 87 |  | 
| Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 88 |       By default, :meth:`timeit` temporarily turns off :term:`garbage collection` | 
 | 89 |       during the timing.  The advantage of this approach is that it makes | 
 | 90 |       independent timings more comparable.  This disadvantage is that GC may be | 
 | 91 |       an important component of the performance of the function being measured. | 
 | 92 |       If so, GC can be re-enabled as the first statement in the *setup* string. | 
 | 93 |       For example:: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 94 |  | 
 | 95 |          timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() | 
 | 96 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 97 |  | 
| Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 98 | The module also defines two convenience functions: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 |  | 
| Georg Brandl | b044b2a | 2009-09-16 16:05:59 +0000 | [diff] [blame] | 100 | .. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 101 |  | 
 | 102 |    Create a :class:`Timer` instance with the given statement, setup code and timer | 
 | 103 |    function and run its :meth:`repeat` method with the given repeat count and | 
 | 104 |    *number* executions. | 
 | 105 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 106 |  | 
| Georg Brandl | b044b2a | 2009-09-16 16:05:59 +0000 | [diff] [blame] | 107 | .. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 108 |  | 
 | 109 |    Create a :class:`Timer` instance with the given statement, setup code and timer | 
 | 110 |    function and run its :meth:`timeit` method with *number* executions. | 
 | 111 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 |  | 
 | 113 | Command Line Interface | 
 | 114 | ---------------------- | 
 | 115 |  | 
 | 116 | When called as a program from the command line, the following form is used:: | 
 | 117 |  | 
 | 118 |    python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] | 
 | 119 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 120 | Where the following options are understood: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 121 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 122 | .. program:: timeit | 
 | 123 |  | 
 | 124 | .. cmdoption:: -n N, --number=N | 
 | 125 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 126 |    how many times to execute 'statement' | 
 | 127 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 128 | .. cmdoption:: -r N, --repeat=N | 
 | 129 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 130 |    how many times to repeat the timer (default 3) | 
 | 131 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 132 | .. cmdoption:: -s S, --setup=S | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 133 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 134 |    statement to be executed once initially (default ``pass``) | 
 | 135 |  | 
 | 136 | .. cmdoption:: -t, --time | 
 | 137 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 138 |    use :func:`time.time` (default on all platforms but Windows) | 
 | 139 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 140 | .. cmdoption:: -c, --clock | 
 | 141 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 142 |    use :func:`time.clock` (default on Windows) | 
 | 143 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 144 | .. cmdoption:: -v, --verbose | 
 | 145 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 146 |    print raw timing results; repeat for more digits precision | 
 | 147 |  | 
| Éric Araujo | 3efdf06 | 2010-12-16 03:16:29 +0000 | [diff] [blame] | 148 | .. cmdoption:: -h, --help | 
 | 149 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 150 |    print a short usage message and exit | 
 | 151 |  | 
 | 152 | A multi-line statement may be given by specifying each line as a separate | 
 | 153 | statement argument; indented lines are possible by enclosing an argument in | 
 | 154 | quotes and using leading spaces.  Multiple :option:`-s` options are treated | 
 | 155 | similarly. | 
 | 156 |  | 
 | 157 | If :option:`-n` is not given, a suitable number of loops is calculated by trying | 
 | 158 | successive powers of 10 until the total time is at least 0.2 seconds. | 
 | 159 |  | 
 | 160 | The default timer function is platform dependent.  On Windows, | 
 | 161 | :func:`time.clock` has microsecond granularity but :func:`time.time`'s | 
 | 162 | granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a | 
 | 163 | second granularity and :func:`time.time` is much more precise.  On either | 
 | 164 | platform, the default timer functions measure wall clock time, not the CPU time. | 
 | 165 | This means that other processes running on the same computer may interfere with | 
 | 166 | the timing.  The best thing to do when accurate timing is necessary is to repeat | 
 | 167 | the timing a few times and use the best time.  The :option:`-r` option is good | 
 | 168 | for this; the default of 3 repetitions is probably enough in most cases.  On | 
 | 169 | Unix, you can use :func:`time.clock` to measure CPU time. | 
 | 170 |  | 
 | 171 | .. note:: | 
 | 172 |  | 
 | 173 |    There is a certain baseline overhead associated with executing a pass statement. | 
 | 174 |    The code here doesn't try to hide it, but you should be aware of it.  The | 
 | 175 |    baseline overhead can be measured by invoking the program without arguments. | 
 | 176 |  | 
 | 177 | The baseline overhead differs between Python versions!  Also, to fairly compare | 
 | 178 | older Python versions to Python 2.3, you may want to use Python's :option:`-O` | 
 | 179 | option for the older versions to avoid timing ``SET_LINENO`` instructions. | 
 | 180 |  | 
 | 181 |  | 
 | 182 | Examples | 
 | 183 | -------- | 
 | 184 |  | 
 | 185 | Here are two example sessions (one using the command line, one using the module | 
 | 186 | interface) that compare the cost of using :func:`hasattr` vs. | 
 | 187 | :keyword:`try`/:keyword:`except` to test for missing and present object | 
 | 188 | attributes. :: | 
 | 189 |  | 
 | 190 |    % timeit.py 'try:' '  str.__bool__' 'except AttributeError:' '  pass' | 
 | 191 |    100000 loops, best of 3: 15.7 usec per loop | 
 | 192 |    % timeit.py 'if hasattr(str, "__bool__"): pass' | 
 | 193 |    100000 loops, best of 3: 4.26 usec per loop | 
 | 194 |    % timeit.py 'try:' '  int.__bool__' 'except AttributeError:' '  pass' | 
 | 195 |    1000000 loops, best of 3: 1.43 usec per loop | 
 | 196 |    % timeit.py 'if hasattr(int, "__bool__"): pass' | 
 | 197 |    100000 loops, best of 3: 2.23 usec per loop | 
 | 198 |  | 
 | 199 | :: | 
 | 200 |  | 
 | 201 |    >>> import timeit | 
 | 202 |    >>> s = """\ | 
 | 203 |    ... try: | 
 | 204 |    ...     str.__bool__ | 
 | 205 |    ... except AttributeError: | 
 | 206 |    ...     pass | 
 | 207 |    ... """ | 
 | 208 |    >>> t = timeit.Timer(stmt=s) | 
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 209 |    >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 |    17.09 usec/pass | 
 | 211 |    >>> s = """\ | 
 | 212 |    ... if hasattr(str, '__bool__'): pass | 
 | 213 |    ... """ | 
 | 214 |    >>> t = timeit.Timer(stmt=s) | 
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 215 |    >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 216 |    4.85 usec/pass | 
 | 217 |    >>> s = """\ | 
 | 218 |    ... try: | 
 | 219 |    ...     int.__bool__ | 
 | 220 |    ... except AttributeError: | 
 | 221 |    ...     pass | 
 | 222 |    ... """ | 
 | 223 |    >>> t = timeit.Timer(stmt=s) | 
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 224 |    >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 225 |    1.97 usec/pass | 
 | 226 |    >>> s = """\ | 
 | 227 |    ... if hasattr(int, '__bool__'): pass | 
 | 228 |    ... """ | 
 | 229 |    >>> t = timeit.Timer(stmt=s) | 
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 230 |    >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 231 |    3.15 usec/pass | 
 | 232 |  | 
 | 233 | To give the :mod:`timeit` module access to functions you define, you can pass a | 
 | 234 | ``setup`` parameter which contains an import statement:: | 
 | 235 |  | 
 | 236 |    def test(): | 
 | 237 |        "Stupid test function" | 
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 238 |        L = [i for i in range(100)] | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 239 |  | 
 | 240 |    if __name__=='__main__': | 
 | 241 |        from timeit import Timer | 
 | 242 |        t = Timer("test()", "from __main__ import test") | 
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 243 |        print(t.timeit()) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 244 |  |