blob: 3387c7f264d289f2dfe8835a0b5cc72938415d37 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +00009.. index::
10 single: Benchmarking
11 single: Performance
12
13This module provides a simple way to time small bits of Python code. It has both
14command line as well as callable interfaces. It avoids a number of common traps
15for measuring execution times. See also Tim Peters' introduction to the
16"Algorithms" chapter in the Python Cookbook, published by O'Reilly.
17
18The module defines the following public class:
19
20
21.. class:: Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])
22
23 Class for timing execution speed of small code snippets.
24
25 The constructor takes a statement to be timed, an additional statement used for
26 setup, and a timer function. Both statements default to ``'pass'``; the timer
27 function is platform-dependent (see the module doc string). The statements may
28 contain newlines, as long as they don't contain multi-line string literals.
29
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
40.. method:: Timer.print_exc([file=None])
41
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
57.. method:: Timer.repeat([repeat=3 [, number=1000000]])
58
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
78.. method:: Timer.timeit([number=1000000])
79
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
88 By default, :meth:`timeit` temporarily turns off garbage collection during the
89 timing. The advantage of this approach is that it makes independent timings
90 more comparable. This disadvantage is that GC may be an important component of
91 the performance of the function being measured. If so, GC can be re-enabled as
92 the first statement in the *setup* string. For example::
93
94 timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
95
96Starting with version 2.6, the module also defines two convenience functions:
97
98
99.. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]])
100
101 Create a :class:`Timer` instance with the given statement, setup code and timer
102 function and run its :meth:`repeat` method with the given repeat count and
103 *number* executions.
104
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106.. function:: timeit(stmt[, setup[, timer[, number=1000000]]])
107
108 Create a :class:`Timer` instance with the given statement, setup code and timer
109 function and run its :meth:`timeit` method with *number* executions.
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112Command Line Interface
113----------------------
114
115When called as a program from the command line, the following form is used::
116
117 python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
118
119where the following options are understood:
120
121-n N/:option:`--number=N`
122 how many times to execute 'statement'
123
124-r N/:option:`--repeat=N`
125 how many times to repeat the timer (default 3)
126
127-s S/:option:`--setup=S`
128 statement to be executed once initially (default ``'pass'``)
129
130-t/:option:`--time`
131 use :func:`time.time` (default on all platforms but Windows)
132
133-c/:option:`--clock`
134 use :func:`time.clock` (default on Windows)
135
136-v/:option:`--verbose`
137 print raw timing results; repeat for more digits precision
138
139-h/:option:`--help`
140 print a short usage message and exit
141
142A multi-line statement may be given by specifying each line as a separate
143statement argument; indented lines are possible by enclosing an argument in
144quotes and using leading spaces. Multiple :option:`-s` options are treated
145similarly.
146
147If :option:`-n` is not given, a suitable number of loops is calculated by trying
148successive powers of 10 until the total time is at least 0.2 seconds.
149
150The default timer function is platform dependent. On Windows,
151:func:`time.clock` has microsecond granularity but :func:`time.time`'s
152granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a
153second granularity and :func:`time.time` is much more precise. On either
154platform, the default timer functions measure wall clock time, not the CPU time.
155This means that other processes running on the same computer may interfere with
156the timing. The best thing to do when accurate timing is necessary is to repeat
157the timing a few times and use the best time. The :option:`-r` option is good
158for this; the default of 3 repetitions is probably enough in most cases. On
159Unix, you can use :func:`time.clock` to measure CPU time.
160
161.. note::
162
163 There is a certain baseline overhead associated with executing a pass statement.
164 The code here doesn't try to hide it, but you should be aware of it. The
165 baseline overhead can be measured by invoking the program without arguments.
166
167The baseline overhead differs between Python versions! Also, to fairly compare
168older Python versions to Python 2.3, you may want to use Python's :option:`-O`
169option for the older versions to avoid timing ``SET_LINENO`` instructions.
170
171
172Examples
173--------
174
175Here are two example sessions (one using the command line, one using the module
176interface) that compare the cost of using :func:`hasattr` vs.
177:keyword:`try`/:keyword:`except` to test for missing and present object
178attributes. ::
179
180 % timeit.py 'try:' ' str.__bool__' 'except AttributeError:' ' pass'
181 100000 loops, best of 3: 15.7 usec per loop
182 % timeit.py 'if hasattr(str, "__bool__"): pass'
183 100000 loops, best of 3: 4.26 usec per loop
184 % timeit.py 'try:' ' int.__bool__' 'except AttributeError:' ' pass'
185 1000000 loops, best of 3: 1.43 usec per loop
186 % timeit.py 'if hasattr(int, "__bool__"): pass'
187 100000 loops, best of 3: 2.23 usec per loop
188
189::
190
191 >>> import timeit
192 >>> s = """\
193 ... try:
194 ... str.__bool__
195 ... except AttributeError:
196 ... pass
197 ... """
198 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000199 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000200 17.09 usec/pass
201 >>> s = """\
202 ... if hasattr(str, '__bool__'): pass
203 ... """
204 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000205 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000206 4.85 usec/pass
207 >>> s = """\
208 ... try:
209 ... int.__bool__
210 ... except AttributeError:
211 ... pass
212 ... """
213 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000214 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000215 1.97 usec/pass
216 >>> s = """\
217 ... if hasattr(int, '__bool__'): pass
218 ... """
219 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000220 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000221 3.15 usec/pass
222
223To give the :mod:`timeit` module access to functions you define, you can pass a
224``setup`` parameter which contains an import statement::
225
226 def test():
227 "Stupid test function"
Collin Winterc79461b2007-09-01 23:34:30 +0000228 L = [i for i in range(100)]
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 if __name__=='__main__':
231 from timeit import Timer
232 t = Timer("test()", "from __main__ import test")
Collin Winterc79461b2007-09-01 23:34:30 +0000233 print(t.timeit())
Georg Brandl116aa622007-08-15 14:28:22 +0000234