blob: 1c4e05bafd4682c24e28276c9b787de32f441682 [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.
34\end{classdesc}
Skip Montanaroca652742003-04-09 01:38:53 +000035
Fred Drakefcd845a2003-04-09 04:06:37 +000036\begin{methoddesc}{print_exc}{\optional{file=\constant{None}}}
Skip Montanaroca652742003-04-09 01:38:53 +000037Helper to print a traceback from the timed code.
38
39Typical 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
49The advantage over the standard traceback is that source lines in the
50compiled template will be displayed.
Fred Drakefcd845a2003-04-09 04:06:37 +000051The optional \var{file} argument directs where the traceback is sent;
52it defaults to \code{sys.stderr}.
Skip Montanaroca652742003-04-09 01:38:53 +000053\end{methoddesc}
54
Raymond Hettinger52136a82003-05-10 03:35:37 +000055\begin{methoddesc}{repeat}{\optional{repeat\code{=3} \optional{,
Fred Drakefcd845a2003-04-09 04:06:37 +000056 number\code{=1000000}}}}
Skip Montanaroca652742003-04-09 01:38:53 +000057Call \method{timeit()} a few times.
58
Fred Drakefcd845a2003-04-09 04:06:37 +000059This is a convenience function that calls the \method{timeit()}
60repeatedly, returning a list of results. The first argument specifies
61how many times to call \method{timeit()}. The second argument
62specifies the \var{number} argument for \function{timeit()}.
Skip Montanaroca652742003-04-09 01:38:53 +000063
Fred Drakefcd845a2003-04-09 04:06:37 +000064\begin{notice}
65It's tempting to calculate mean and standard deviation from the result
Skip Montanaroca652742003-04-09 01:38:53 +000066vector and report these. However, this is not very useful. In a typical
67case, the lowest value gives a lower bound for how fast your machine can run
68the given code snippet; higher values in the result vector are typically not
69caused by variability in Python's speed, but by other processes interfering
70with your timing accuracy. So the \function{min()} of the result is
71probably the only number you should be interested in. After that, you
72should look at the entire vector and apply common sense rather than
73statistics.
Fred Drakefcd845a2003-04-09 04:06:37 +000074\end{notice}
Skip Montanaroca652742003-04-09 01:38:53 +000075\end{methoddesc}
76
Fred Drakefcd845a2003-04-09 04:06:37 +000077\begin{methoddesc}{timeit}{\optional{number\code{=1000000}}}
78Time \var{number} executions of the main statement.
79This executes the setup statement once, and then
80returns the time it takes to execute the main statement a number of
81times, measured in seconds as a float. The argument is the number of
82times through the loop, defaulting to one million. The main
83statement, the setup statement and the timer function to be used are
84passed to the constructor.
Raymond Hettingerc14149e2004-01-04 21:19:18 +000085
86\begin{notice}
87By default, \method{timeit()} temporarily turns off garbage collection
88during the timing. The advantage of this approach is that it makes
89independent timings more comparable. This disadvantage is that GC
90may be an important component of the performance of the function being
91measured. If so, GC can be re-enabled as the first statement in the
92\var{setup} string. For example:
93\begin{verbatim}
94 timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()
95\end{verbatim}
96\end{notice}
Skip Montanaroca652742003-04-09 01:38:53 +000097\end{methoddesc}
Fred Drakefcd845a2003-04-09 04:06:37 +000098
Skip Montanaroca652742003-04-09 01:38:53 +000099
100\subsection{Command Line Interface}
101
102When called as a program from the command line, the following form is used:
103
104\begin{verbatim}
Fred Drakefcd845a2003-04-09 04:06:37 +0000105python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
Skip Montanaroca652742003-04-09 01:38:53 +0000106\end{verbatim}
107
108where the following options are understood:
109
110\begin{description}
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000111\item[-n N/\longprogramopt{number=N}] how many times to execute 'statement'
112\item[-r N/\longprogramopt{repeat=N}] how many times to repeat the timer (default 3)
113\item[-s S/\longprogramopt{setup=S}] statement to be executed once initially (default
Fred Drakefcd845a2003-04-09 04:06:37 +0000114\code{'pass'})
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000115\item[-t/\longprogramopt{time}] use \function{time.time()}
Fred Drakefcd845a2003-04-09 04:06:37 +0000116(default on all platforms but Windows)
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000117\item[-c/\longprogramopt{clock}] use \function{time.clock()} (default on Windows)
118\item[-v/\longprogramopt{verbose}] print raw timing results; repeat for more digits
Fred Drakefcd845a2003-04-09 04:06:37 +0000119precision
Raymond Hettinger9d12ab52003-08-31 04:20:12 +0000120\item[-h/\longprogramopt{help}] print a short usage message and exit
Skip Montanaroca652742003-04-09 01:38:53 +0000121\end{description}
122
Fred Drakefcd845a2003-04-09 04:06:37 +0000123A multi-line statement may be given by specifying each line as a
124separate statement argument; indented lines are possible by enclosing
125an argument in quotes and using leading spaces. Multiple
126\programopt{-s} options are treated similarly.
Skip Montanaroca652742003-04-09 01:38:53 +0000127
Fred Drakefcd845a2003-04-09 04:06:37 +0000128If \programopt{-n} is not given, a suitable number of loops is
129calculated by trying successive powers of 10 until the total time is
130at least 0.2 seconds.
Skip Montanaroca652742003-04-09 01:38:53 +0000131
Fred Drakefcd845a2003-04-09 04:06:37 +0000132The default timer function is platform dependent. On Windows,
133\function{time.clock()} has microsecond granularity but
134\function{time.time()}'s granularity is 1/60th of a second; on \UNIX,
135\function{time.clock()} has 1/100th of a second granularity and
136\function{time.time()} is much more precise. On either platform, the
Martin v. Löwis7bdc4842003-09-20 11:09:28 +0000137default timer functions measure wall clock time, not the CPU time.
Fred Drakefcd845a2003-04-09 04:06:37 +0000138This means that other processes running on the same computer may
139interfere with the timing. The best thing to do when accurate timing
140is necessary is to repeat the timing a few times and use the best
141time. The \programopt{-r} option is good for this; the default of 3
142repetitions is probably enough in most cases. On \UNIX, you can use
143\function{time.clock()} to measure CPU time.
Skip Montanaroca652742003-04-09 01:38:53 +0000144
Fred Drakefcd845a2003-04-09 04:06:37 +0000145\begin{notice}
146 There is a certain baseline overhead associated with executing a
147 pass statement. The code here doesn't try to hide it, but you
148 should be aware of it. The baseline overhead can be measured by
149 invoking the program without arguments.
150\end{notice}
Skip Montanaroca652742003-04-09 01:38:53 +0000151
Fred Drakefcd845a2003-04-09 04:06:37 +0000152The baseline overhead differs between Python versions! Also, to
153fairly compare older Python versions to Python 2.3, you may want to
154use Python's \programopt{-O} option for the older versions to avoid
155timing \code{SET_LINENO} instructions.
Skip Montanaroca652742003-04-09 01:38:53 +0000156
157\subsection{Examples}
158
Fred Drakefcd845a2003-04-09 04:06:37 +0000159Here are two example sessions (one using the command line, one using
160the module interface) that compare the cost of using
161\function{hasattr()} vs. \keyword{try}/\keyword{except} to test for
162missing and present object attributes.
Skip Montanaroca652742003-04-09 01:38:53 +0000163
164\begin{verbatim}
Fred Drakefcd845a2003-04-09 04:06:37 +0000165% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
Skip Montanaroca652742003-04-09 01:38:53 +0000166100000 loops, best of 3: 15.7 usec per loop
Fred Drakefcd845a2003-04-09 04:06:37 +0000167% timeit.py 'if hasattr(str, "__nonzero__"): pass'
Skip Montanaroca652742003-04-09 01:38:53 +0000168100000 loops, best of 3: 4.26 usec per loop
Fred Drakefcd845a2003-04-09 04:06:37 +0000169% timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
Skip Montanaroca652742003-04-09 01:38:53 +00001701000000 loops, best of 3: 1.43 usec per loop
Fred Drakefcd845a2003-04-09 04:06:37 +0000171% timeit.py 'if hasattr(int, "__nonzero__"): pass'
Skip Montanaroca652742003-04-09 01:38:53 +0000172100000 loops, best of 3: 2.23 usec per loop
173\end{verbatim}
174
175\begin{verbatim}
176>>> import timeit
177>>> s = """\
178... try:
Fred Drakefcd845a2003-04-09 04:06:37 +0000179... str.__nonzero__
Skip Montanaroca652742003-04-09 01:38:53 +0000180... except AttributeError:
Fred Drakefcd845a2003-04-09 04:06:37 +0000181... pass
Skip Montanaroca652742003-04-09 01:38:53 +0000182... """
183>>> t = timeit.Timer(stmt=s)
184>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
18517.09 usec/pass
186>>> s = """\
187... if hasattr(str, '__nonzero__'): pass
188... """
189>>> t = timeit.Timer(stmt=s)
190>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
1914.85 usec/pass
192>>> s = """\
193... try:
Fred Drakefcd845a2003-04-09 04:06:37 +0000194... int.__nonzero__
Skip Montanaroca652742003-04-09 01:38:53 +0000195... except AttributeError:
Fred Drakefcd845a2003-04-09 04:06:37 +0000196... pass
Skip Montanaroca652742003-04-09 01:38:53 +0000197... """
198>>> t = timeit.Timer(stmt=s)
199>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
2001.97 usec/pass
201>>> s = """\
202... if hasattr(int, '__nonzero__'): pass
203... """
204>>> t = timeit.Timer(stmt=s)
205>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
2063.15 usec/pass
207\end{verbatim}
Skip Montanaroa30dffb2003-05-09 18:21:02 +0000208
209To give the \module{timeit} module access to functions you
210define, you can pass a \code{setup} parameter which contains an import
211statement:
212
213\begin{verbatim}
214def test():
215 "Stupid test function"
216 L = []
217 for i in range(100):
218 L.append(i)
219
220if __name__=='__main__':
221 from timeit import Timer
222 t = Timer("test()", "from __main__ import test")
223 print t.timeit()
224\end{verbatim}