|
| 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 | + |
| 7 | +\index{Benchmarking} |
| 8 | +\index{Performance} |
| 9 | + |
| 10 | +\versionadded{2.3} |
| 11 | + |
| 12 | +This module provides a simple way to time small bits of Python code. It has |
| 13 | +both command line as well as callable interfaces. It avoids a number of |
| 14 | +common traps for measuring execution times. See also Tim Peters' |
| 15 | +introduction to the Algorithms chapter in the ``Python Cookbook'', published |
| 16 | +by O'Reilly. |
| 17 | + |
| 18 | +The module interface defines the following public class: |
| 19 | + |
| 20 | +\begin{classdesc}{Timer}{\optional{stmt='pass' |
| 21 | + \optional{, setup='pass' |
| 22 | + \optional{, timer=<timer function>}}}} |
| 23 | +Class for timing execution speed of small code snippets. |
| 24 | + |
| 25 | +The constructor takes a statement to be timed, an additional statement used |
| 26 | +for setup, and a timer function. Both statements default to 'pass'; the |
| 27 | +timer function is platform-dependent (see the module doc string). |
| 28 | + |
| 29 | +To measure the execution time of the first statement, use the timeit() |
| 30 | +method. The repeat() method is a convenience to call timeit() multiple |
| 31 | +times and return a list of results. |
| 32 | + |
| 33 | +The statements may contain newlines, as long as they don't contain |
| 34 | +multi-line string literals. |
| 35 | + |
| 36 | +\begin{methoddesc}{print_exc}{\optional{file=None}} |
| 37 | +Helper to print a traceback from the timed code. |
| 38 | + |
| 39 | +Typical use: |
| 40 | + |
| 41 | +\begin{verbatim} |
| 42 | + t = Timer(...) # outside the try/except |
| 43 | + try: |
| 44 | + t.timeit(...) # or t.repeat(...) |
| 45 | + except: |
| 46 | + t.print_exc() |
| 47 | +\end{verbatim} |
| 48 | + |
| 49 | +The advantage over the standard traceback is that source lines in the |
| 50 | +compiled template will be displayed. |
| 51 | + |
| 52 | +The optional file argument directs where the traceback is sent; it defaults |
| 53 | +to \code{sys.stderr}. |
| 54 | +\end{methoddesc} |
| 55 | + |
| 56 | +\begin{methoddesc}{repeat}{\optional{repeat=3\optional{, number=1000000}}} |
| 57 | +Call \method{timeit()} a few times. |
| 58 | + |
| 59 | +This is a convenience function that calls the \method{timeit()} repeatedly, |
| 60 | +returning a list of results. The first argument specifies how many times to |
| 61 | +call \function{timeit()}. The second argument specifies the \code{number} |
| 62 | +argument for \function{timeit()}. |
| 63 | + |
| 64 | +Note: it's tempting to calculate mean and standard deviation from the result |
| 65 | +vector and report these. However, this is not very useful. In a typical |
| 66 | +case, the lowest value gives a lower bound for how fast your machine can run |
| 67 | +the given code snippet; higher values in the result vector are typically not |
| 68 | +caused by variability in Python's speed, but by other processes interfering |
| 69 | +with your timing accuracy. So the \function{min()} of the result is |
| 70 | +probably the only number you should be interested in. After that, you |
| 71 | +should look at the entire vector and apply common sense rather than |
| 72 | +statistics. |
| 73 | +\end{methoddesc} |
| 74 | + |
| 75 | +\begin{methoddesc}{timeit}{\optional{number=1000000}} |
| 76 | +Time \code{number} executions of the main statement. |
| 77 | + |
| 78 | +To be precise, this executes the setup statement once, and then returns the |
| 79 | +time it takes to execute the main statement a number of times, as a float |
| 80 | +measured in seconds. The argument is the number of times through the loop, |
| 81 | +defaulting to one million. The main statement, the setup statement and the |
| 82 | +timer function to be used are passed to the constructor. |
| 83 | +\end{methoddesc} |
| 84 | +\end{classdesc} |
| 85 | + |
| 86 | +\subsection{Command Line Interface} |
| 87 | + |
| 88 | +When called as a program from the command line, the following form is used: |
| 89 | + |
| 90 | +\begin{verbatim} |
| 91 | + python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] |
| 92 | +\end{verbatim} |
| 93 | + |
| 94 | +where the following options are understood: |
| 95 | + |
| 96 | +\begin{description} |
| 97 | +\item[-n N/--number=N] how many times to execute 'statement' |
| 98 | +\item[-r N/--repeat=N] how many times to repeat the timer (default 3) |
| 99 | +\item[-s S/--setup=S] statement to be executed once initially (default |
| 100 | +'pass') |
| 101 | +\item[-t/--time] use time.time() (default on all platforms but Windows) |
| 102 | +\item[-c/--clock] use time.clock() (default on Windows) |
| 103 | +\item[-v/--verbose] print raw timing results; repeat for more digits |
| 104 | +precision |
| 105 | +\item[-h/--help] print a short usage message and exit |
| 106 | +\end{description} |
| 107 | + |
| 108 | +A multi-line statement may be given by specifying each line as a separate |
| 109 | +statement argument; indented lines are possible by enclosing an argument in |
| 110 | +quotes and using leading spaces. Multiple -s options are treated similarly. |
| 111 | + |
| 112 | +If -n is not given, a suitable number of loops is calculated by trying |
| 113 | +successive powers of 10 until the total time is at least 0.2 seconds. |
| 114 | + |
| 115 | +The default timer function is platform dependent. On Windows, clock() has |
| 116 | +microsecond granularity but time()'s granularity is 1/60th of a second; on |
| 117 | +Unix, clock() has 1/100th of a second granularity and time() is much more |
| 118 | +precise. On either platform, the default timer functions measures wall |
| 119 | +clock time, not the CPU time. This means that other processes running on |
| 120 | +the same computer may interfere with the timing. The best thing to do when |
| 121 | +accurate timing is necessary is to repeat the timing a few times and use the |
| 122 | +best time. The -r option is good for this; the default of 3 repetitions is |
| 123 | +probably enough in most cases. On Unix, you can use clock() to measure CPU |
| 124 | +time. |
| 125 | + |
| 126 | +Note: there is a certain baseline overhead associated with executing a pass |
| 127 | +statement. The code here doesn't try to hide it, but you should be aware of |
| 128 | +it. The baseline overhead can be measured by invoking the program without |
| 129 | +arguments. |
| 130 | + |
| 131 | +The baseline overhead differs between Python versions! Also, to fairly |
| 132 | +compare older Python versions to Python 2.3, you may want to use python -O |
| 133 | +for the older versions to avoid timing SET_LINENO instructions. |
| 134 | + |
| 135 | +\subsection{Examples} |
| 136 | + |
| 137 | +Here are two example sessions (one using the command line, one using the |
| 138 | +module interface) that compare the cost of using \function{hasattr()} |
| 139 | +vs. try/except to test for missing and present object attributes. |
| 140 | + |
| 141 | +\begin{verbatim} |
| 142 | +\% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' |
| 143 | +100000 loops, best of 3: 15.7 usec per loop |
| 144 | +\% timeit.py 'if hasattr(str, "__nonzero__"): pass' |
| 145 | +100000 loops, best of 3: 4.26 usec per loop |
| 146 | +\% timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' |
| 147 | +1000000 loops, best of 3: 1.43 usec per loop |
| 148 | +\% timeit.py 'if hasattr(int, "__nonzero__"): pass' |
| 149 | +100000 loops, best of 3: 2.23 usec per loop |
| 150 | +\end{verbatim} |
| 151 | + |
| 152 | +\begin{verbatim} |
| 153 | +>>> import timeit |
| 154 | +>>> s = """\ |
| 155 | +... try: |
| 156 | +... str.__nonzero__ |
| 157 | +... except AttributeError: |
| 158 | +... pass |
| 159 | +... """ |
| 160 | +>>> t = timeit.Timer(stmt=s) |
| 161 | +>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) |
| 162 | +17.09 usec/pass |
| 163 | +>>> s = """\ |
| 164 | +... if hasattr(str, '__nonzero__'): pass |
| 165 | +... """ |
| 166 | +>>> t = timeit.Timer(stmt=s) |
| 167 | +>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) |
| 168 | +4.85 usec/pass |
| 169 | +>>> s = """\ |
| 170 | +... try: |
| 171 | +... int.__nonzero__ |
| 172 | +... except AttributeError: |
| 173 | +... pass |
| 174 | +... """ |
| 175 | +>>> t = timeit.Timer(stmt=s) |
| 176 | +>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) |
| 177 | +1.97 usec/pass |
| 178 | +>>> s = """\ |
| 179 | +... if hasattr(int, '__nonzero__'): pass |
| 180 | +... """ |
| 181 | +>>> t = timeit.Timer(stmt=s) |
| 182 | +>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) |
| 183 | +3.15 usec/pass |
| 184 | +\end{verbatim} |
0 commit comments