blob: 29a941c185f7377e537fe28631a7ed22f325b113 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
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
15This module provides a simple way to time small bits of Python code. It has both
16command line as well as callable interfaces. It avoids a number of common traps
17for measuring execution times. See also Tim Peters' introduction to the
18"Algorithms" chapter in the Python Cookbook, published by O'Reilly.
19
20The 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 Melotti1dfd5d92009-06-27 23:45:39 +000029 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 Melottib4ad3952009-06-28 00:07:45 +000031 they don't contain multi-line string literals.
Georg Brandl8ec7f652007-08-15 14:28:01 +000032
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 Brandl584265b2007-12-02 14:58:50 +000092 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 Brandl8ec7f652007-08-15 14:28:01 +000098
99 timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()
100
101Starting 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
121Command Line Interface
122----------------------
123
124When 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
Éric Araujoa8132ec2010-12-16 03:53:53 +0000128Where the following options are understood:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129
Éric Araujoa8132ec2010-12-16 03:53:53 +0000130.. program:: timeit
131
132.. cmdoption:: -n N, --number=N
133
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134 how many times to execute 'statement'
135
Éric Araujoa8132ec2010-12-16 03:53:53 +0000136.. cmdoption:: -r N, --repeat=N
137
Georg Brandl8ec7f652007-08-15 14:28:01 +0000138 how many times to repeat the timer (default 3)
139
Éric Araujoa8132ec2010-12-16 03:53:53 +0000140.. cmdoption:: -s S, --setup=S
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141
Éric Araujoa8132ec2010-12-16 03:53:53 +0000142 statement to be executed once initially (default ``pass``)
143
144.. cmdoption:: -t, --time
145
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146 use :func:`time.time` (default on all platforms but Windows)
147
Éric Araujoa8132ec2010-12-16 03:53:53 +0000148.. cmdoption:: -c, --clock
149
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150 use :func:`time.clock` (default on Windows)
151
Éric Araujoa8132ec2010-12-16 03:53:53 +0000152.. cmdoption:: -v, --verbose
153
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154 print raw timing results; repeat for more digits precision
155
Éric Araujoa8132ec2010-12-16 03:53:53 +0000156.. cmdoption:: -h, --help
157
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158 print a short usage message and exit
159
160A multi-line statement may be given by specifying each line as a separate
161statement argument; indented lines are possible by enclosing an argument in
162quotes and using leading spaces. Multiple :option:`-s` options are treated
163similarly.
164
165If :option:`-n` is not given, a suitable number of loops is calculated by trying
166successive powers of 10 until the total time is at least 0.2 seconds.
167
168The default timer function is platform dependent. On Windows,
169:func:`time.clock` has microsecond granularity but :func:`time.time`'s
170granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a
171second granularity and :func:`time.time` is much more precise. On either
172platform, the default timer functions measure wall clock time, not the CPU time.
173This means that other processes running on the same computer may interfere with
174the timing. The best thing to do when accurate timing is necessary is to repeat
175the timing a few times and use the best time. The :option:`-r` option is good
176for this; the default of 3 repetitions is probably enough in most cases. On
177Unix, you can use :func:`time.clock` to measure CPU time.
178
179.. note::
180
181 There is a certain baseline overhead associated with executing a pass statement.
182 The code here doesn't try to hide it, but you should be aware of it. The
183 baseline overhead can be measured by invoking the program without arguments.
184
185The baseline overhead differs between Python versions! Also, to fairly compare
186older Python versions to Python 2.3, you may want to use Python's :option:`-O`
187option for the older versions to avoid timing ``SET_LINENO`` instructions.
188
189
190Examples
191--------
192
193Here are two example sessions (one using the command line, one using the module
194interface) that compare the cost of using :func:`hasattr` vs.
195:keyword:`try`/:keyword:`except` to test for missing and present object
196attributes. ::
197
198 % timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
199 100000 loops, best of 3: 15.7 usec per loop
200 % timeit.py 'if hasattr(str, "__nonzero__"): pass'
201 100000 loops, best of 3: 4.26 usec per loop
202 % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
203 1000000 loops, best of 3: 1.43 usec per loop
204 % timeit.py 'if hasattr(int, "__nonzero__"): pass'
205 100000 loops, best of 3: 2.23 usec per loop
206
207::
208
209 >>> import timeit
210 >>> s = """\
211 ... try:
212 ... str.__nonzero__
213 ... except AttributeError:
214 ... pass
215 ... """
216 >>> t = timeit.Timer(stmt=s)
217 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
218 17.09 usec/pass
219 >>> s = """\
220 ... if hasattr(str, '__nonzero__'): pass
221 ... """
222 >>> t = timeit.Timer(stmt=s)
223 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
224 4.85 usec/pass
225 >>> s = """\
226 ... try:
227 ... int.__nonzero__
228 ... except AttributeError:
229 ... pass
230 ... """
231 >>> t = timeit.Timer(stmt=s)
232 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
233 1.97 usec/pass
234 >>> s = """\
235 ... if hasattr(int, '__nonzero__'): pass
236 ... """
237 >>> t = timeit.Timer(stmt=s)
238 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
239 3.15 usec/pass
240
241To give the :mod:`timeit` module access to functions you define, you can pass a
242``setup`` parameter which contains an import statement::
243
244 def test():
245 "Stupid test function"
246 L = []
247 for i in range(100):
248 L.append(i)
249
250 if __name__=='__main__':
251 from timeit import Timer
252 t = Timer("test()", "from __main__ import test")
253 print t.timeit()
254