blob: 968728f58ffbefd7b6a3a9b335916483826f70d5 [file] [log] [blame]
Skip Montanaroca652742003-04-09 01:38:53 +00001\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 Drakefcd845a2003-04-09 04:06:37 +00007\versionadded{2.3}
Skip Montanaroca652742003-04-09 01:38:53 +00008\index{Benchmarking}
9\index{Performance}
10
Fred Drakefcd845a2003-04-09 04:06:37 +000011This module provides a simple way to time small bits of Python code.
12It has both command line as well as callable interfaces. It avoids a
13number of common traps for measuring execution times. See also Tim
14Peters' introduction to the ``Algorithms'' chapter in the
15\citetitle{Python Cookbook}, published by O'Reilly.
Skip Montanaroca652742003-04-09 01:38:53 +000016
Fred Drakefcd845a2003-04-09 04:06:37 +000017The module defines the following public class:
Skip Montanaroca652742003-04-09 01:38:53 +000018
Fred Drakefcd845a2003-04-09 04:06:37 +000019\begin{classdesc}{Timer}{\optional{stmt=\code{'pass'}
20 \optional{, setup=\code{'pass'}
21 \optional{, timer=<timer function>}}}}
Skip Montanaroca652742003-04-09 01:38:53 +000022Class for timing execution speed of small code snippets.
23
Fred Drakefcd845a2003-04-09 04:06:37 +000024The constructor takes a statement to be timed, an additional statement
25used for setup, and a timer function. Both statements default to
26\code{'pass'}; the timer function is platform-dependent (see the
27module doc string). The statements may contain newlines, as long as
28they don't contain multi-line string literals.
Skip Montanaroca652742003-04-09 01:38:53 +000029
Fred Drakefcd845a2003-04-09 04:06:37 +000030To measure the execution time of the first statement, use the
31\method{timeit()} method. The \method{repeat()} method is a
32convenience to call \method{timeit()} multiple times and return a list
33of results.
Guido van Rossumd8faa362007-04-27 19:54:29 +000034
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 Drakefcd845a2003-04-09 04:06:37 +000041\end{classdesc}
Skip Montanaroca652742003-04-09 01:38:53 +000042
Fred Drakefcd845a2003-04-09 04:06:37 +000043\begin{methoddesc}{print_exc}{\optional{file=\constant{None}}}
Skip Montanaroca652742003-04-09 01:38:53 +000044Helper to print a traceback from the timed code.
45
46Typical 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
56The advantage over the standard traceback is that source lines in the
57compiled template will be displayed.
Fred Drakefcd845a2003-04-09 04:06:37 +000058The optional \var{file} argument directs where the traceback is sent;
59it defaults to \code{sys.stderr}.
Skip Montanaroca652742003-04-09 01:38:53 +000060\end{methoddesc}
61
Raymond Hettinger52136a82003-05-10 03:35:37 +000062\begin{methoddesc}{repeat}{\optional{repeat\code{=3} \optional{,
Fred Drakefcd845a2003-04-09 04:06:37 +000063 number\code{=1000000}}}}
Skip Montanaroca652742003-04-09 01:38:53 +000064Call \method{timeit()} a few times.
65
Fred Drakefcd845a2003-04-09 04:06:37 +000066This is a convenience function that calls the \method{timeit()}
67repeatedly, returning a list of results. The first argument specifies
68how many times to call \method{timeit()}. The second argument
69specifies the \var{number} argument for \function{timeit()}.
Skip Montanaroca652742003-04-09 01:38:53 +000070
Fred Drakefcd845a2003-04-09 04:06:37 +000071\begin{notice}
72It's tempting to calculate mean and standard deviation from the result
Skip Montanaroca652742003-04-09 01:38:53 +000073vector and report these. However, this is not very useful. In a typical
74case, the lowest value gives a lower bound for how fast your machine can run
75the given code snippet; higher values in the result vector are typically not
76caused by variability in Python's speed, but by other processes interfering
77with your timing accuracy. So the \function{min()} of the result is
78probably the only number you should be interested in. After that, you
79should look at the entire vector and apply common sense rather than
80statistics.
Fred Drakefcd845a2003-04-09 04:06:37 +000081\end{notice}
Skip Montanaroca652742003-04-09 01:38:53 +000082\end{methoddesc}
83
Fred Drakefcd845a2003-04-09 04:06:37 +000084\begin{methoddesc}{timeit}{\optional{number\code{=1000000}}}
85Time \var{number} executions of the main statement.
86This executes the setup statement once, and then
87returns the time it takes to execute the main statement a number of
88times, measured in seconds as a float. The argument is the number of
89times through the loop, defaulting to one million. The main
90statement, the setup statement and the timer function to be used are
91passed to the constructor.
Raymond Hettingerc14149e2004-01-04 21:19:18 +000092
93\begin{notice}
94By default, \method{timeit()} temporarily turns off garbage collection
95during the timing. The advantage of this approach is that it makes
96independent timings more comparable. This disadvantage is that GC
97may be an important component of the performance of the function being
98measured. If so, GC can be re-enabled as the first statement in the
99\var{setup} string. For example:
100\begin{verbatim}
Guido van Rossum805365e2007-05-07 22:24:25 +0000101 timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
Raymond Hettingerc14149e2004-01-04 21:19:18 +0000102\end{verbatim}
103\end{notice}
Skip Montanaroca652742003-04-09 01:38:53 +0000104\end{methoddesc}
Fred Drakefcd845a2003-04-09 04:06:37 +0000105
Skip Montanaroca652742003-04-09 01:38:53 +0000106
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107Starting 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}}}}}}
111Create a \class{Timer} instance with the given statement, setup code and timer
112function 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}}}}}
119Create a \class{Timer} instance with the given statement, setup code and timer
120function and run its \method{timeit} method with \var{number} executions.
121\versionadded{2.6}
122\end{funcdesc}
123
124
Skip Montanaroca652742003-04-09 01:38:53 +0000125\subsection{Command Line Interface}
126
127When called as a program from the command line, the following form is used:
128
129\begin{verbatim}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
Skip Montanaroca652742003-04-09 01:38:53 +0000131\end{verbatim}
132
133where the following options are understood:
134
135\begin{description}
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000136\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 Drakefcd845a2003-04-09 04:06:37 +0000139\code{'pass'})
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000140\item[-t/\longprogramopt{time}] use \function{time.time()}
Fred Drakefcd845a2003-04-09 04:06:37 +0000141(default on all platforms but Windows)
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000142\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 Drakefcd845a2003-04-09 04:06:37 +0000144precision
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000145\item[-h/\longprogramopt{help}] print a short usage message and exit
Skip Montanaroca652742003-04-09 01:38:53 +0000146\end{description}
147
Fred Drakefcd845a2003-04-09 04:06:37 +0000148A multi-line statement may be given by specifying each line as a
149separate statement argument; indented lines are possible by enclosing
150an argument in quotes and using leading spaces. Multiple
151\programopt{-s} options are treated similarly.
Skip Montanaroca652742003-04-09 01:38:53 +0000152
Fred Drakefcd845a2003-04-09 04:06:37 +0000153If \programopt{-n} is not given, a suitable number of loops is
154calculated by trying successive powers of 10 until the total time is
155at least 0.2 seconds.
Skip Montanaroca652742003-04-09 01:38:53 +0000156
Fred Drakefcd845a2003-04-09 04:06:37 +0000157The 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öwis7bdc4842003-09-20 11:09:28 +0000162default timer functions measure wall clock time, not the CPU time.
Fred Drakefcd845a2003-04-09 04:06:37 +0000163This means that other processes running on the same computer may
164interfere with the timing. The best thing to do when accurate timing
165is necessary is to repeat the timing a few times and use the best
166time. The \programopt{-r} option is good for this; the default of 3
167repetitions is probably enough in most cases. On \UNIX, you can use
168\function{time.clock()} to measure CPU time.
Skip Montanaroca652742003-04-09 01:38:53 +0000169
Fred Drakefcd845a2003-04-09 04:06:37 +0000170\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 Montanaroca652742003-04-09 01:38:53 +0000176
Fred Drakefcd845a2003-04-09 04:06:37 +0000177The baseline overhead differs between Python versions! Also, to
178fairly compare older Python versions to Python 2.3, you may want to
179use Python's \programopt{-O} option for the older versions to avoid
180timing \code{SET_LINENO} instructions.
Skip Montanaroca652742003-04-09 01:38:53 +0000181
182\subsection{Examples}
183
Fred Drakefcd845a2003-04-09 04:06:37 +0000184Here are two example sessions (one using the command line, one using
185the module interface) that compare the cost of using
186\function{hasattr()} vs. \keyword{try}/\keyword{except} to test for
187missing and present object attributes.
Skip Montanaroca652742003-04-09 01:38:53 +0000188
189\begin{verbatim}
Jack Diederich4dafcc42006-11-28 19:15:13 +0000190% timeit.py 'try:' ' str.__bool__' 'except AttributeError:' ' pass'
Skip Montanaroca652742003-04-09 01:38:53 +0000191100000 loops, best of 3: 15.7 usec per loop
Jack Diederich4dafcc42006-11-28 19:15:13 +0000192% timeit.py 'if hasattr(str, "__bool__"): pass'
Skip Montanaroca652742003-04-09 01:38:53 +0000193100000 loops, best of 3: 4.26 usec per loop
Jack Diederich4dafcc42006-11-28 19:15:13 +0000194% timeit.py 'try:' ' int.__bool__' 'except AttributeError:' ' pass'
Skip Montanaroca652742003-04-09 01:38:53 +00001951000000 loops, best of 3: 1.43 usec per loop
Jack Diederich4dafcc42006-11-28 19:15:13 +0000196% timeit.py 'if hasattr(int, "__bool__"): pass'
Skip Montanaroca652742003-04-09 01:38:53 +0000197100000 loops, best of 3: 2.23 usec per loop
198\end{verbatim}
199
200\begin{verbatim}
201>>> import timeit
202>>> s = """\
203... try:
Jack Diederich4dafcc42006-11-28 19:15:13 +0000204... str.__bool__
Skip Montanaroca652742003-04-09 01:38:53 +0000205... except AttributeError:
Fred Drakefcd845a2003-04-09 04:06:37 +0000206... pass
Skip Montanaroca652742003-04-09 01:38:53 +0000207... """
208>>> t = timeit.Timer(stmt=s)
209>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
21017.09 usec/pass
211>>> s = """\
Jack Diederich4dafcc42006-11-28 19:15:13 +0000212... if hasattr(str, '__bool__'): pass
Skip Montanaroca652742003-04-09 01:38:53 +0000213... """
214>>> t = timeit.Timer(stmt=s)
215>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
2164.85 usec/pass
217>>> s = """\
218... try:
Jack Diederich4dafcc42006-11-28 19:15:13 +0000219... int.__bool__
Skip Montanaroca652742003-04-09 01:38:53 +0000220... except AttributeError:
Fred Drakefcd845a2003-04-09 04:06:37 +0000221... pass
Skip Montanaroca652742003-04-09 01:38:53 +0000222... """
223>>> t = timeit.Timer(stmt=s)
224>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
2251.97 usec/pass
226>>> s = """\
Jack Diederich4dafcc42006-11-28 19:15:13 +0000227... if hasattr(int, '__bool__'): pass
Skip Montanaroca652742003-04-09 01:38:53 +0000228... """
229>>> t = timeit.Timer(stmt=s)
230>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
2313.15 usec/pass
232\end{verbatim}
Skip Montanaroa30dffb2003-05-09 18:21:02 +0000233
234To give the \module{timeit} module access to functions you
235define, you can pass a \code{setup} parameter which contains an import
236statement:
237
238\begin{verbatim}
239def test():
240 "Stupid test function"
241 L = []
242 for i in range(100):
243 L.append(i)
244
245if __name__=='__main__':
246 from timeit import Timer
247 t = Timer("test()", "from __main__ import test")
248 print t.timeit()
249\end{verbatim}