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