Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`timeit` --- Measure execution time of small code snippets |
| 3 | =============================================================== |
| 4 | |
| 5 | .. module:: timeit |
| 6 | :synopsis: Measure the execution time of small code snippets. |
| 7 | |
| 8 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | .. index:: |
| 10 | single: Benchmarking |
| 11 | single: Performance |
| 12 | |
| 13 | This module provides a simple way to time small bits of Python code. It has both |
| 14 | command line as well as callable interfaces. It avoids a number of common traps |
| 15 | for measuring execution times. See also Tim Peters' introduction to the |
| 16 | "Algorithms" chapter in the Python Cookbook, published by O'Reilly. |
| 17 | |
| 18 | The module defines the following public class: |
| 19 | |
| 20 | |
| 21 | .. class:: Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]]) |
| 22 | |
| 23 | Class for timing execution speed of small code snippets. |
| 24 | |
| 25 | The constructor takes a statement to be timed, an additional statement used for |
| 26 | setup, and a timer function. Both statements default to ``'pass'``; the timer |
| 27 | function is platform-dependent (see the module doc string). The statements may |
| 28 | contain newlines, as long as they don't contain multi-line string literals. |
| 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 | |
| 40 | .. method:: Timer.print_exc([file=None]) |
| 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 | |
| 57 | .. method:: Timer.repeat([repeat=3 [, number=1000000]]) |
| 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 | |
| 78 | .. method:: Timer.timeit([number=1000000]) |
| 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 | |
| 100 | .. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]]) |
| 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 | |
| 107 | .. function:: timeit(stmt[, setup[, timer[, number=1000000]]]) |
| 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 | |
| 120 | where the following options are understood: |
| 121 | |
| 122 | -n N/:option:`--number=N` |
| 123 | how many times to execute 'statement' |
| 124 | |
| 125 | -r N/:option:`--repeat=N` |
| 126 | how many times to repeat the timer (default 3) |
| 127 | |
| 128 | -s S/:option:`--setup=S` |
| 129 | statement to be executed once initially (default ``'pass'``) |
| 130 | |
| 131 | -t/:option:`--time` |
| 132 | use :func:`time.time` (default on all platforms but Windows) |
| 133 | |
| 134 | -c/:option:`--clock` |
| 135 | use :func:`time.clock` (default on Windows) |
| 136 | |
| 137 | -v/:option:`--verbose` |
| 138 | print raw timing results; repeat for more digits precision |
| 139 | |
| 140 | -h/:option:`--help` |
| 141 | print a short usage message and exit |
| 142 | |
| 143 | A multi-line statement may be given by specifying each line as a separate |
| 144 | statement argument; indented lines are possible by enclosing an argument in |
| 145 | quotes and using leading spaces. Multiple :option:`-s` options are treated |
| 146 | similarly. |
| 147 | |
| 148 | If :option:`-n` is not given, a suitable number of loops is calculated by trying |
| 149 | successive powers of 10 until the total time is at least 0.2 seconds. |
| 150 | |
| 151 | The default timer function is platform dependent. On Windows, |
| 152 | :func:`time.clock` has microsecond granularity but :func:`time.time`'s |
| 153 | granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a |
| 154 | second granularity and :func:`time.time` is much more precise. On either |
| 155 | platform, the default timer functions measure wall clock time, not the CPU time. |
| 156 | This means that other processes running on the same computer may interfere with |
| 157 | the timing. The best thing to do when accurate timing is necessary is to repeat |
| 158 | the timing a few times and use the best time. The :option:`-r` option is good |
| 159 | for this; the default of 3 repetitions is probably enough in most cases. On |
| 160 | Unix, you can use :func:`time.clock` to measure CPU time. |
| 161 | |
| 162 | .. note:: |
| 163 | |
| 164 | There is a certain baseline overhead associated with executing a pass statement. |
| 165 | The code here doesn't try to hide it, but you should be aware of it. The |
| 166 | baseline overhead can be measured by invoking the program without arguments. |
| 167 | |
| 168 | The baseline overhead differs between Python versions! Also, to fairly compare |
| 169 | older Python versions to Python 2.3, you may want to use Python's :option:`-O` |
| 170 | option for the older versions to avoid timing ``SET_LINENO`` instructions. |
| 171 | |
| 172 | |
| 173 | Examples |
| 174 | -------- |
| 175 | |
| 176 | Here are two example sessions (one using the command line, one using the module |
| 177 | interface) that compare the cost of using :func:`hasattr` vs. |
| 178 | :keyword:`try`/:keyword:`except` to test for missing and present object |
| 179 | attributes. :: |
| 180 | |
| 181 | % timeit.py 'try:' ' str.__bool__' 'except AttributeError:' ' pass' |
| 182 | 100000 loops, best of 3: 15.7 usec per loop |
| 183 | % timeit.py 'if hasattr(str, "__bool__"): pass' |
| 184 | 100000 loops, best of 3: 4.26 usec per loop |
| 185 | % timeit.py 'try:' ' int.__bool__' 'except AttributeError:' ' pass' |
| 186 | 1000000 loops, best of 3: 1.43 usec per loop |
| 187 | % timeit.py 'if hasattr(int, "__bool__"): pass' |
| 188 | 100000 loops, best of 3: 2.23 usec per loop |
| 189 | |
| 190 | :: |
| 191 | |
| 192 | >>> import timeit |
| 193 | >>> s = """\ |
| 194 | ... try: |
| 195 | ... str.__bool__ |
| 196 | ... except AttributeError: |
| 197 | ... pass |
| 198 | ... """ |
| 199 | >>> t = timeit.Timer(stmt=s) |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 200 | >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 201 | 17.09 usec/pass |
| 202 | >>> s = """\ |
| 203 | ... if hasattr(str, '__bool__'): pass |
| 204 | ... """ |
| 205 | >>> t = timeit.Timer(stmt=s) |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 206 | >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | 4.85 usec/pass |
| 208 | >>> s = """\ |
| 209 | ... try: |
| 210 | ... int.__bool__ |
| 211 | ... except AttributeError: |
| 212 | ... 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 | 1.97 usec/pass |
| 217 | >>> s = """\ |
| 218 | ... if hasattr(int, '__bool__'): pass |
| 219 | ... """ |
| 220 | >>> t = timeit.Timer(stmt=s) |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 221 | >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | 3.15 usec/pass |
| 223 | |
| 224 | To give the :mod:`timeit` module access to functions you define, you can pass a |
| 225 | ``setup`` parameter which contains an import statement:: |
| 226 | |
| 227 | def test(): |
| 228 | "Stupid test function" |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 229 | L = [i for i in range(100)] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 230 | |
| 231 | if __name__=='__main__': |
| 232 | from timeit import Timer |
| 233 | t = Timer("test()", "from __main__ import test") |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 234 | print(t.timeit()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 235 | |