blob: f1f7a5aab84889408d410074bb5f8d3c05c8e80f [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`timeit` --- Measure execution time of small code snippets
2===============================================================
3
4.. module:: timeit
5 :synopsis: Measure the execution time of small code snippets.
6
7
8.. versionadded:: 2.3
9
10.. index::
11 single: Benchmarking
12 single: Performance
13
Éric Araujo29a0b572011-08-19 02:14:03 +020014**Source code:** :source:`Lib/timeit.py`
15
16--------------
17
Georg Brandl8ec7f652007-08-15 14:28:01 +000018This module provides a simple way to time small bits of Python code. It has both
19command line as well as callable interfaces. It avoids a number of common traps
20for measuring execution times. See also Tim Peters' introduction to the
21"Algorithms" chapter in the Python Cookbook, published by O'Reilly.
22
23The module defines the following public class:
24
25
Ezio Melottiaea83f52012-09-20 06:02:50 +030026.. class:: Timer(stmt='pass', setup='pass', timer=<timer function>)
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28 Class for timing execution speed of small code snippets.
29
30 The constructor takes a statement to be timed, an additional statement used for
31 setup, and a timer function. Both statements default to ``'pass'``; the timer
Ezio Melotti1dfd5d92009-06-27 23:45:39 +000032 function is platform-dependent (see the module doc string). *stmt* and *setup*
33 may also contain multiple statements separated by ``;`` or newlines, as long as
Ezio Melottib4ad3952009-06-28 00:07:45 +000034 they don't contain multi-line string literals.
Georg Brandl8ec7f652007-08-15 14:28:01 +000035
Ezio Melottiaea83f52012-09-20 06:02:50 +030036 To measure the execution time of the first statement, use the :meth:`Timer.timeit`
37 method. The :meth:`repeat` method is a convenience to call :meth:`.timeit`
Georg Brandl8ec7f652007-08-15 14:28:01 +000038 multiple times and return a list of results.
39
40 .. versionchanged:: 2.6
41 The *stmt* and *setup* parameters can now also take objects that are callable
42 without arguments. This will embed calls to them in a timer function that will
Ezio Melottiaea83f52012-09-20 06:02:50 +030043 then be executed by :meth:`.timeit`. Note that the timing overhead is a
44 little larger in this case because of the extra function calls.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46
Ezio Melottiaea83f52012-09-20 06:02:50 +030047.. method:: Timer.print_exc(file=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +000048
49 Helper to print a traceback from the timed code.
50
51 Typical use::
52
53 t = Timer(...) # outside the try/except
54 try:
55 t.timeit(...) # or t.repeat(...)
56 except:
57 t.print_exc()
58
59 The advantage over the standard traceback is that source lines in the compiled
60 template will be displayed. The optional *file* argument directs where the
61 traceback is sent; it defaults to ``sys.stderr``.
62
63
Ezio Melottiaea83f52012-09-20 06:02:50 +030064.. method:: Timer.repeat(repeat=3, number=1000000)
Georg Brandl8ec7f652007-08-15 14:28:01 +000065
Ezio Melottiaea83f52012-09-20 06:02:50 +030066 Call :meth:`.timeit` a few times.
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
Ezio Melottiaea83f52012-09-20 06:02:50 +030068 This is a convenience function that calls the :meth:`.timeit` repeatedly,
Georg Brandl8ec7f652007-08-15 14:28:01 +000069 returning a list of results. The first argument specifies how many times to
Ezio Melottiaea83f52012-09-20 06:02:50 +030070 call :meth:`.timeit`. The second argument specifies the *number* argument for
71 :meth:`.timeit`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
73 .. note::
74
75 It's tempting to calculate mean and standard deviation from the result vector
76 and report these. However, this is not very useful. In a typical case, the
77 lowest value gives a lower bound for how fast your machine can run the given
78 code snippet; higher values in the result vector are typically not caused by
79 variability in Python's speed, but by other processes interfering with your
80 timing accuracy. So the :func:`min` of the result is probably the only number
81 you should be interested in. After that, you should look at the entire vector
82 and apply common sense rather than statistics.
83
84
Ezio Melottiaea83f52012-09-20 06:02:50 +030085.. method:: Timer.timeit(number=1000000)
Georg Brandl8ec7f652007-08-15 14:28:01 +000086
87 Time *number* executions of the main statement. This executes the setup
88 statement once, and then returns the time it takes to execute the main statement
89 a number of times, measured in seconds as a float. The argument is the number
90 of times through the loop, defaulting to one million. The main statement, the
91 setup statement and the timer function to be used are passed to the constructor.
92
93 .. note::
94
Ezio Melottiaea83f52012-09-20 06:02:50 +030095 By default, :meth:`.timeit` temporarily turns off :term:`garbage collection`
Georg Brandl584265b2007-12-02 14:58:50 +000096 during the timing. The advantage of this approach is that it makes
97 independent timings more comparable. This disadvantage is that GC may be
98 an important component of the performance of the function being measured.
99 If so, GC can be re-enabled as the first statement in the *setup* string.
100 For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101
102 timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()
103
Sandro Tosi3f0f5772012-04-24 18:11:29 +0200104The module also defines three convenience functions:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000105
106
Sandro Tosi3f0f5772012-04-24 18:11:29 +0200107.. function:: default_timer()
108
109 Define a default timer, in a platform specific manner. On Windows,
110 :func:`time.clock` has microsecond granularity but :func:`time.time`'s
111 granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of
112 a second granularity and :func:`time.time` is much more precise. On either
113 platform, :func:`default_timer` measures wall clock time, not the CPU
114 time. This means that other processes running on the same computer may
115 interfere with the timing.
116
Hynek Schlawacke58ce012012-05-22 10:27:40 +0200117.. function:: repeat(stmt, setup='pass', timer=default_timer, repeat=3 , number=1000000)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118
119 Create a :class:`Timer` instance with the given statement, setup code and timer
120 function and run its :meth:`repeat` method with the given repeat count and
121 *number* executions.
122
123 .. versionadded:: 2.6
124
125
Hynek Schlawacke58ce012012-05-22 10:27:40 +0200126.. function:: timeit(stmt, setup='pass', timer=default_timer, number=1000000)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128 Create a :class:`Timer` instance with the given statement, setup code and timer
Ezio Melottiaea83f52012-09-20 06:02:50 +0300129 function and run its :meth:`.timeit` method with *number* executions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
131 .. versionadded:: 2.6
132
133
134Command Line Interface
135----------------------
136
137When called as a program from the command line, the following form is used::
138
139 python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
140
Éric Araujoa8132ec2010-12-16 03:53:53 +0000141Where the following options are understood:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
Éric Araujoa8132ec2010-12-16 03:53:53 +0000143.. program:: timeit
144
145.. cmdoption:: -n N, --number=N
146
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147 how many times to execute 'statement'
148
Éric Araujoa8132ec2010-12-16 03:53:53 +0000149.. cmdoption:: -r N, --repeat=N
150
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151 how many times to repeat the timer (default 3)
152
Éric Araujoa8132ec2010-12-16 03:53:53 +0000153.. cmdoption:: -s S, --setup=S
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154
Éric Araujoa8132ec2010-12-16 03:53:53 +0000155 statement to be executed once initially (default ``pass``)
156
157.. cmdoption:: -t, --time
158
Georg Brandl8ec7f652007-08-15 14:28:01 +0000159 use :func:`time.time` (default on all platforms but Windows)
160
Éric Araujoa8132ec2010-12-16 03:53:53 +0000161.. cmdoption:: -c, --clock
162
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163 use :func:`time.clock` (default on Windows)
164
Éric Araujoa8132ec2010-12-16 03:53:53 +0000165.. cmdoption:: -v, --verbose
166
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167 print raw timing results; repeat for more digits precision
168
Éric Araujoa8132ec2010-12-16 03:53:53 +0000169.. cmdoption:: -h, --help
170
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171 print a short usage message and exit
172
173A multi-line statement may be given by specifying each line as a separate
174statement argument; indented lines are possible by enclosing an argument in
175quotes and using leading spaces. Multiple :option:`-s` options are treated
176similarly.
177
178If :option:`-n` is not given, a suitable number of loops is calculated by trying
179successive powers of 10 until the total time is at least 0.2 seconds.
180
Sandro Tosi3f0f5772012-04-24 18:11:29 +0200181:func:`default_timer` measurations can be affected by other programs running on
182the same machine, so
183the best thing to do when accurate timing is necessary is to repeat
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184the timing a few times and use the best time. The :option:`-r` option is good
185for this; the default of 3 repetitions is probably enough in most cases. On
186Unix, you can use :func:`time.clock` to measure CPU time.
187
188.. note::
189
190 There is a certain baseline overhead associated with executing a pass statement.
191 The code here doesn't try to hide it, but you should be aware of it. The
192 baseline overhead can be measured by invoking the program without arguments.
193
194The baseline overhead differs between Python versions! Also, to fairly compare
195older Python versions to Python 2.3, you may want to use Python's :option:`-O`
196option for the older versions to avoid timing ``SET_LINENO`` instructions.
197
198
199Examples
200--------
201
202Here are two example sessions (one using the command line, one using the module
203interface) that compare the cost of using :func:`hasattr` vs.
204:keyword:`try`/:keyword:`except` to test for missing and present object
205attributes. ::
206
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800207 $ python -m timeit 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208 100000 loops, best of 3: 15.7 usec per loop
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800209 $ python -m timeit 'if hasattr(str, "__nonzero__"): pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000210 100000 loops, best of 3: 4.26 usec per loop
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800211 $ python -m timeit 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000212 1000000 loops, best of 3: 1.43 usec per loop
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800213 $ python -m timeit 'if hasattr(int, "__nonzero__"): pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000214 100000 loops, best of 3: 2.23 usec per loop
215
216::
217
218 >>> import timeit
219 >>> s = """\
220 ... try:
221 ... str.__nonzero__
222 ... except AttributeError:
223 ... pass
224 ... """
225 >>> t = timeit.Timer(stmt=s)
226 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
227 17.09 usec/pass
228 >>> s = """\
229 ... if hasattr(str, '__nonzero__'): pass
230 ... """
231 >>> t = timeit.Timer(stmt=s)
232 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
233 4.85 usec/pass
234 >>> s = """\
235 ... try:
236 ... int.__nonzero__
237 ... except AttributeError:
238 ... pass
239 ... """
240 >>> t = timeit.Timer(stmt=s)
241 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
242 1.97 usec/pass
243 >>> s = """\
244 ... if hasattr(int, '__nonzero__'): pass
245 ... """
246 >>> t = timeit.Timer(stmt=s)
247 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
248 3.15 usec/pass
249
250To give the :mod:`timeit` module access to functions you define, you can pass a
Ezio Melottiaea83f52012-09-20 06:02:50 +0300251*setup* parameter which contains an import statement::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
253 def test():
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800254 """Stupid test function"""
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255 L = []
256 for i in range(100):
257 L.append(i)
258
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800259 if __name__ == '__main__':
Georg Brandl8ec7f652007-08-15 14:28:01 +0000260 from timeit import Timer
261 t = Timer("test()", "from __main__ import test")
262 print t.timeit()
263