blob: 4a0b9c257b1c35a78d4ebb5a17d639cd57ed53ef [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +00008.. index::
9 single: Benchmarking
10 single: Performance
11
12This module provides a simple way to time small bits of Python code. It has both
13command line as well as callable interfaces. It avoids a number of common traps
14for measuring execution times. See also Tim Peters' introduction to the
15"Algorithms" chapter in the Python Cookbook, published by O'Reilly.
16
17The module defines the following public class:
18
19
Georg Brandl7f01a132009-09-16 15:58:14 +000020.. class:: Timer(stmt='pass', setup='pass', timer=<timer function>)
Georg Brandl116aa622007-08-15 14:28:22 +000021
22 Class for timing execution speed of small code snippets.
23
24 The constructor takes a statement to be timed, an additional statement used for
25 setup, and a timer function. Both statements default to ``'pass'``; the timer
Benjamin Peterson0289b152009-06-28 17:22:03 +000026 function is platform-dependent (see the module doc string). *stmt* and *setup*
27 may also contain multiple statements separated by ``;`` or newlines, as long as
28 they don't contain multi-line string literals.
Georg Brandl116aa622007-08-15 14:28:22 +000029
30 To measure the execution time of the first statement, use the :meth:`timeit`
31 method. The :meth:`repeat` method is a convenience to call :meth:`timeit`
32 multiple times and return a list of results.
33
Georg Brandl55ac8f02007-09-01 13:51:09 +000034 The *stmt* and *setup* parameters can also take objects that are callable
35 without arguments. This will embed calls to them in a timer function that
36 will then be executed by :meth:`timeit`. Note that the timing overhead is a
37 little larger in this case because of the extra function calls.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39
Georg Brandl7f01a132009-09-16 15:58:14 +000040.. method:: Timer.print_exc(file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 Helper to print a traceback from the timed code.
43
44 Typical use::
45
46 t = Timer(...) # outside the try/except
47 try:
48 t.timeit(...) # or t.repeat(...)
49 except:
50 t.print_exc()
51
52 The advantage over the standard traceback is that source lines in the compiled
53 template will be displayed. The optional *file* argument directs where the
54 traceback is sent; it defaults to ``sys.stderr``.
55
56
Georg Brandl7f01a132009-09-16 15:58:14 +000057.. method:: Timer.repeat(repeat=3, number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +000058
59 Call :meth:`timeit` a few times.
60
61 This is a convenience function that calls the :meth:`timeit` repeatedly,
62 returning a list of results. The first argument specifies how many times to
63 call :meth:`timeit`. The second argument specifies the *number* argument for
64 :func:`timeit`.
65
66 .. note::
67
68 It's tempting to calculate mean and standard deviation from the result vector
69 and report these. However, this is not very useful. In a typical case, the
70 lowest value gives a lower bound for how fast your machine can run the given
71 code snippet; higher values in the result vector are typically not caused by
72 variability in Python's speed, but by other processes interfering with your
73 timing accuracy. So the :func:`min` of the result is probably the only number
74 you should be interested in. After that, you should look at the entire vector
75 and apply common sense rather than statistics.
76
77
Georg Brandl7f01a132009-09-16 15:58:14 +000078.. method:: Timer.timeit(number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +000079
80 Time *number* executions of the main statement. This executes the setup
81 statement once, and then returns the time it takes to execute the main statement
82 a number of times, measured in seconds as a float. The argument is the number
83 of times through the loop, defaulting to one million. The main statement, the
84 setup statement and the timer function to be used are passed to the constructor.
85
86 .. note::
87
Christian Heimesd8654cf2007-12-02 15:22:16 +000088 By default, :meth:`timeit` temporarily turns off :term:`garbage collection`
89 during the timing. The advantage of this approach is that it makes
90 independent timings more comparable. This disadvantage is that GC may be
91 an important component of the performance of the function being measured.
92 If so, GC can be re-enabled as the first statement in the *setup* string.
93 For example::
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
96
Georg Brandl116aa622007-08-15 14:28:22 +000097
Georg Brandle6bcc912008-05-12 18:05:20 +000098The module also defines two convenience functions:
Georg Brandl116aa622007-08-15 14:28:22 +000099
Georg Brandl7f01a132009-09-16 15:58:14 +0000100.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 Create a :class:`Timer` instance with the given statement, setup code and timer
103 function and run its :meth:`repeat` method with the given repeat count and
104 *number* executions.
105
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Georg Brandl7f01a132009-09-16 15:58:14 +0000107.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109 Create a :class:`Timer` instance with the given statement, setup code and timer
110 function and run its :meth:`timeit` method with *number* executions.
111
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113Command Line Interface
114----------------------
115
116When called as a program from the command line, the following form is used::
117
118 python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
119
Éric Araujo713d3032010-11-18 16:38:46 +0000120Where the following options are understood:
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Éric Araujo713d3032010-11-18 16:38:46 +0000122.. program:: timeit
123
124.. cmdoption:: -n N, --number=N
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126 how many times to execute 'statement'
127
Éric Araujo713d3032010-11-18 16:38:46 +0000128.. cmdoption:: -r N, --repeat=N
129
Georg Brandl116aa622007-08-15 14:28:22 +0000130 how many times to repeat the timer (default 3)
131
Éric Araujo713d3032010-11-18 16:38:46 +0000132.. cmdoption:: -s S, --setup=S
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Éric Araujo713d3032010-11-18 16:38:46 +0000134 statement to be executed once initially (default ``pass``)
135
136.. cmdoption:: -t, --time
137
Georg Brandl116aa622007-08-15 14:28:22 +0000138 use :func:`time.time` (default on all platforms but Windows)
139
Éric Araujo713d3032010-11-18 16:38:46 +0000140.. cmdoption:: -c, --clock
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142 use :func:`time.clock` (default on Windows)
143
Éric Araujo713d3032010-11-18 16:38:46 +0000144.. cmdoption:: -v, --verbose
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146 print raw timing results; repeat for more digits precision
147
Éric Araujo713d3032010-11-18 16:38:46 +0000148.. cmdoption:: -h, --help
149
Georg Brandl116aa622007-08-15 14:28:22 +0000150 print a short usage message and exit
151
152A multi-line statement may be given by specifying each line as a separate
153statement argument; indented lines are possible by enclosing an argument in
154quotes and using leading spaces. Multiple :option:`-s` options are treated
155similarly.
156
157If :option:`-n` is not given, a suitable number of loops is calculated by trying
158successive powers of 10 until the total time is at least 0.2 seconds.
159
160The default timer function is platform dependent. On Windows,
161:func:`time.clock` has microsecond granularity but :func:`time.time`'s
162granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a
163second granularity and :func:`time.time` is much more precise. On either
164platform, the default timer functions measure wall clock time, not the CPU time.
165This means that other processes running on the same computer may interfere with
166the timing. The best thing to do when accurate timing is necessary is to repeat
167the timing a few times and use the best time. The :option:`-r` option is good
168for this; the default of 3 repetitions is probably enough in most cases. On
169Unix, you can use :func:`time.clock` to measure CPU time.
170
171.. note::
172
173 There is a certain baseline overhead associated with executing a pass statement.
174 The code here doesn't try to hide it, but you should be aware of it. The
175 baseline overhead can be measured by invoking the program without arguments.
176
177The baseline overhead differs between Python versions! Also, to fairly compare
178older Python versions to Python 2.3, you may want to use Python's :option:`-O`
179option for the older versions to avoid timing ``SET_LINENO`` instructions.
180
181
182Examples
183--------
184
185Here are two example sessions (one using the command line, one using the module
186interface) that compare the cost of using :func:`hasattr` vs.
187:keyword:`try`/:keyword:`except` to test for missing and present object
188attributes. ::
189
190 % timeit.py 'try:' ' str.__bool__' 'except AttributeError:' ' pass'
191 100000 loops, best of 3: 15.7 usec per loop
192 % timeit.py 'if hasattr(str, "__bool__"): pass'
193 100000 loops, best of 3: 4.26 usec per loop
194 % timeit.py 'try:' ' int.__bool__' 'except AttributeError:' ' pass'
195 1000000 loops, best of 3: 1.43 usec per loop
196 % timeit.py 'if hasattr(int, "__bool__"): pass'
197 100000 loops, best of 3: 2.23 usec per loop
198
199::
200
201 >>> import timeit
202 >>> s = """\
203 ... try:
204 ... str.__bool__
205 ... except AttributeError:
206 ... pass
207 ... """
208 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000209 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000210 17.09 usec/pass
211 >>> s = """\
212 ... if hasattr(str, '__bool__'): pass
213 ... """
214 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000215 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000216 4.85 usec/pass
217 >>> s = """\
218 ... try:
219 ... int.__bool__
220 ... except AttributeError:
221 ... pass
222 ... """
223 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000224 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000225 1.97 usec/pass
226 >>> s = """\
227 ... if hasattr(int, '__bool__'): pass
228 ... """
229 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000230 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000231 3.15 usec/pass
232
233To give the :mod:`timeit` module access to functions you define, you can pass a
234``setup`` parameter which contains an import statement::
235
236 def test():
237 "Stupid test function"
Collin Winterc79461b2007-09-01 23:34:30 +0000238 L = [i for i in range(100)]
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240 if __name__=='__main__':
241 from timeit import Timer
242 t = Timer("test()", "from __main__ import test")
Collin Winterc79461b2007-09-01 23:34:30 +0000243 print(t.timeit())
Georg Brandl116aa622007-08-15 14:28:22 +0000244