blob: 7fbe19e9fc63d79a64bf6bf646fe0903fb1698b2 [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
26.. class:: Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])
27
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
36 To measure the execution time of the first statement, use the :meth:`timeit`
37 method. The :meth:`repeat` method is a convenience to call :meth:`timeit`
38 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
43 then be executed by :meth:`timeit`. Note that the timing overhead is a little
44 larger in this case because of the extra function calls.
45
46
47.. method:: Timer.print_exc([file=None])
48
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
64.. method:: Timer.repeat([repeat=3 [, number=1000000]])
65
66 Call :meth:`timeit` a few times.
67
68 This is a convenience function that calls the :meth:`timeit` repeatedly,
69 returning a list of results. The first argument specifies how many times to
70 call :meth:`timeit`. The second argument specifies the *number* argument for
71 :func:`timeit`.
72
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
85.. method:: Timer.timeit([number=1000000])
86
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
Georg Brandl584265b2007-12-02 14:58:50 +000095 By default, :meth:`timeit` temporarily turns off :term:`garbage collection`
96 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
104Starting with version 2.6, the module also defines two convenience functions:
105
106
107.. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]])
108
109 Create a :class:`Timer` instance with the given statement, setup code and timer
110 function and run its :meth:`repeat` method with the given repeat count and
111 *number* executions.
112
113 .. versionadded:: 2.6
114
115
116.. function:: timeit(stmt[, setup[, timer[, number=1000000]]])
117
118 Create a :class:`Timer` instance with the given statement, setup code and timer
119 function and run its :meth:`timeit` method with *number* executions.
120
121 .. versionadded:: 2.6
122
123
124Command Line Interface
125----------------------
126
127When called as a program from the command line, the following form is used::
128
129 python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
130
Éric Araujoa8132ec2010-12-16 03:53:53 +0000131Where the following options are understood:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
Éric Araujoa8132ec2010-12-16 03:53:53 +0000133.. program:: timeit
134
135.. cmdoption:: -n N, --number=N
136
Georg Brandl8ec7f652007-08-15 14:28:01 +0000137 how many times to execute 'statement'
138
Éric Araujoa8132ec2010-12-16 03:53:53 +0000139.. cmdoption:: -r N, --repeat=N
140
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141 how many times to repeat the timer (default 3)
142
Éric Araujoa8132ec2010-12-16 03:53:53 +0000143.. cmdoption:: -s S, --setup=S
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144
Éric Araujoa8132ec2010-12-16 03:53:53 +0000145 statement to be executed once initially (default ``pass``)
146
147.. cmdoption:: -t, --time
148
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149 use :func:`time.time` (default on all platforms but Windows)
150
Éric Araujoa8132ec2010-12-16 03:53:53 +0000151.. cmdoption:: -c, --clock
152
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153 use :func:`time.clock` (default on Windows)
154
Éric Araujoa8132ec2010-12-16 03:53:53 +0000155.. cmdoption:: -v, --verbose
156
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157 print raw timing results; repeat for more digits precision
158
Éric Araujoa8132ec2010-12-16 03:53:53 +0000159.. cmdoption:: -h, --help
160
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161 print a short usage message and exit
162
163A multi-line statement may be given by specifying each line as a separate
164statement argument; indented lines are possible by enclosing an argument in
165quotes and using leading spaces. Multiple :option:`-s` options are treated
166similarly.
167
168If :option:`-n` is not given, a suitable number of loops is calculated by trying
169successive powers of 10 until the total time is at least 0.2 seconds.
170
171The default timer function is platform dependent. On Windows,
172:func:`time.clock` has microsecond granularity but :func:`time.time`'s
173granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a
174second granularity and :func:`time.time` is much more precise. On either
175platform, the default timer functions measure wall clock time, not the CPU time.
176This means that other processes running on the same computer may interfere with
177the timing. The best thing to do when accurate timing is necessary is to repeat
178the timing a few times and use the best time. The :option:`-r` option is good
179for this; the default of 3 repetitions is probably enough in most cases. On
180Unix, you can use :func:`time.clock` to measure CPU time.
181
182.. note::
183
184 There is a certain baseline overhead associated with executing a pass statement.
185 The code here doesn't try to hide it, but you should be aware of it. The
186 baseline overhead can be measured by invoking the program without arguments.
187
188The baseline overhead differs between Python versions! Also, to fairly compare
189older Python versions to Python 2.3, you may want to use Python's :option:`-O`
190option for the older versions to avoid timing ``SET_LINENO`` instructions.
191
192
193Examples
194--------
195
196Here are two example sessions (one using the command line, one using the module
197interface) that compare the cost of using :func:`hasattr` vs.
198:keyword:`try`/:keyword:`except` to test for missing and present object
199attributes. ::
200
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800201 $ python -m timeit 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202 100000 loops, best of 3: 15.7 usec per loop
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800203 $ python -m timeit 'if hasattr(str, "__nonzero__"): pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204 100000 loops, best of 3: 4.26 usec per loop
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800205 $ python -m timeit 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206 1000000 loops, best of 3: 1.43 usec per loop
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800207 $ python -m timeit 'if hasattr(int, "__nonzero__"): pass'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208 100000 loops, best of 3: 2.23 usec per loop
209
210::
211
212 >>> import timeit
213 >>> s = """\
214 ... try:
215 ... str.__nonzero__
216 ... except AttributeError:
217 ... pass
218 ... """
219 >>> t = timeit.Timer(stmt=s)
220 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
221 17.09 usec/pass
222 >>> s = """\
223 ... if hasattr(str, '__nonzero__'): pass
224 ... """
225 >>> t = timeit.Timer(stmt=s)
226 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
227 4.85 usec/pass
228 >>> s = """\
229 ... try:
230 ... int.__nonzero__
231 ... except AttributeError:
232 ... pass
233 ... """
234 >>> t = timeit.Timer(stmt=s)
235 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
236 1.97 usec/pass
237 >>> s = """\
238 ... if hasattr(int, '__nonzero__'): pass
239 ... """
240 >>> t = timeit.Timer(stmt=s)
241 >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
242 3.15 usec/pass
243
244To give the :mod:`timeit` module access to functions you define, you can pass a
245``setup`` parameter which contains an import statement::
246
247 def test():
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800248 """Stupid test function"""
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249 L = []
250 for i in range(100):
251 L.append(i)
252
Senthil Kumaranb8b71722011-08-06 13:34:30 +0800253 if __name__ == '__main__':
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254 from timeit import Timer
255 t = Timer("test()", "from __main__ import test")
256 print t.timeit()
257