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