blob: cd2d205b99f417859fe03de1c514139e5483d543 [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
Raymond Hettingera1993682011-01-27 01:20:32 +000012**Source code:** :source:`Lib/timeit.py`
13
14--------------
15
Georg Brandl116aa622007-08-15 14:28:22 +000016This module provides a simple way to time small bits of Python code. It has both
17command line as well as callable interfaces. It avoids a number of common traps
18for measuring execution times. See also Tim Peters' introduction to the
19"Algorithms" chapter in the Python Cookbook, published by O'Reilly.
20
21The module defines the following public class:
22
23
Georg Brandl7f01a132009-09-16 15:58:14 +000024.. class:: Timer(stmt='pass', setup='pass', timer=<timer function>)
Georg Brandl116aa622007-08-15 14:28:22 +000025
26 Class for timing execution speed of small code snippets.
27
28 The constructor takes a statement to be timed, an additional statement used for
29 setup, and a timer function. Both statements default to ``'pass'``; the timer
Benjamin Peterson0289b152009-06-28 17:22:03 +000030 function is platform-dependent (see the module doc string). *stmt* and *setup*
31 may also contain multiple statements separated by ``;`` or newlines, as long as
32 they don't contain multi-line string literals.
Georg Brandl116aa622007-08-15 14:28:22 +000033
34 To measure the execution time of the first statement, use the :meth:`timeit`
35 method. The :meth:`repeat` method is a convenience to call :meth:`timeit`
36 multiple times and return a list of results.
37
Georg Brandl55ac8f02007-09-01 13:51:09 +000038 The *stmt* and *setup* parameters can also take objects that are callable
39 without arguments. This will embed calls to them in a timer function that
40 will then be executed by :meth:`timeit`. Note that the timing overhead is a
41 little larger in this case because of the extra function calls.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43
Georg Brandl7f01a132009-09-16 15:58:14 +000044.. method:: Timer.print_exc(file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000045
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
Georg Brandl7f01a132009-09-16 15:58:14 +000061.. method:: Timer.repeat(repeat=3, number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +000062
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
Georg Brandl7f01a132009-09-16 15:58:14 +000082.. method:: Timer.timeit(number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +000083
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
Christian Heimesd8654cf2007-12-02 15:22:16 +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 Brandl116aa622007-08-15 14:28:22 +000098
99 timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Sandro Tosie6c34622012-04-24 18:11:46 +0200102The module also defines three convenience functions:
103
104
105.. function:: default_timer()
106
107 Define a default timer, in a platform specific manner. On Windows,
108 :func:`time.clock` has microsecond granularity but :func:`time.time`'s
109 granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of
110 a second granularity and :func:`time.time` is much more precise. On either
111 platform, :func:`default_timer` measures wall clock time, not the CPU
112 time. This means that other processes running on the same computer may
113 interfere with the timing.
114
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandl7f01a132009-09-16 15:58:14 +0000116.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 Create a :class:`Timer` instance with the given statement, setup code and timer
119 function and run its :meth:`repeat` method with the given repeat count and
120 *number* executions.
121
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Georg Brandl7f01a132009-09-16 15:58:14 +0000123.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 Create a :class:`Timer` instance with the given statement, setup code and timer
126 function and run its :meth:`timeit` method with *number* executions.
127
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129Command Line Interface
130----------------------
131
132When called as a program from the command line, the following form is used::
133
134 python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
135
Éric Araujo713d3032010-11-18 16:38:46 +0000136Where the following options are understood:
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Éric Araujo713d3032010-11-18 16:38:46 +0000138.. program:: timeit
139
140.. cmdoption:: -n N, --number=N
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142 how many times to execute 'statement'
143
Éric Araujo713d3032010-11-18 16:38:46 +0000144.. cmdoption:: -r N, --repeat=N
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146 how many times to repeat the timer (default 3)
147
Éric Araujo713d3032010-11-18 16:38:46 +0000148.. cmdoption:: -s S, --setup=S
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Éric Araujo713d3032010-11-18 16:38:46 +0000150 statement to be executed once initially (default ``pass``)
151
152.. cmdoption:: -t, --time
153
Georg Brandl116aa622007-08-15 14:28:22 +0000154 use :func:`time.time` (default on all platforms but Windows)
155
Éric Araujo713d3032010-11-18 16:38:46 +0000156.. cmdoption:: -c, --clock
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158 use :func:`time.clock` (default on Windows)
159
Éric Araujo713d3032010-11-18 16:38:46 +0000160.. cmdoption:: -v, --verbose
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162 print raw timing results; repeat for more digits precision
163
Éric Araujo713d3032010-11-18 16:38:46 +0000164.. cmdoption:: -h, --help
165
Georg Brandl116aa622007-08-15 14:28:22 +0000166 print a short usage message and exit
167
168A multi-line statement may be given by specifying each line as a separate
169statement argument; indented lines are possible by enclosing an argument in
170quotes and using leading spaces. Multiple :option:`-s` options are treated
171similarly.
172
173If :option:`-n` is not given, a suitable number of loops is calculated by trying
174successive powers of 10 until the total time is at least 0.2 seconds.
175
Sandro Tosie6c34622012-04-24 18:11:46 +0200176:func:`default_timer` measurations can be affected by other programs running on
177the same machine, so
178the best thing to do when accurate timing is necessary is to repeat
Georg Brandl116aa622007-08-15 14:28:22 +0000179the timing a few times and use the best time. The :option:`-r` option is good
180for this; the default of 3 repetitions is probably enough in most cases. On
181Unix, you can use :func:`time.clock` to measure CPU time.
182
183.. note::
184
185 There is a certain baseline overhead associated with executing a pass statement.
186 The code here doesn't try to hide it, but you should be aware of it. The
187 baseline overhead can be measured by invoking the program without arguments.
188
189The baseline overhead differs between Python versions! Also, to fairly compare
190older Python versions to Python 2.3, you may want to use Python's :option:`-O`
191option for the older versions to avoid timing ``SET_LINENO`` instructions.
192
193
194Examples
195--------
196
197Here are two example sessions (one using the command line, one using the module
198interface) that compare the cost of using :func:`hasattr` vs.
199:keyword:`try`/:keyword:`except` to test for missing and present object
200attributes. ::
201
Senthil Kumaran2e015352011-08-06 13:37:04 +0800202 $ python -m timeit 'try:' ' str.__bool__' 'except AttributeError:' ' pass'
Georg Brandl116aa622007-08-15 14:28:22 +0000203 100000 loops, best of 3: 15.7 usec per loop
Senthil Kumaran2e015352011-08-06 13:37:04 +0800204 $ python -m timeit 'if hasattr(str, "__bool__"): pass'
Georg Brandl116aa622007-08-15 14:28:22 +0000205 100000 loops, best of 3: 4.26 usec per loop
Senthil Kumaran2e015352011-08-06 13:37:04 +0800206 $ python -m timeit 'try:' ' int.__bool__' 'except AttributeError:' ' pass'
Georg Brandl116aa622007-08-15 14:28:22 +0000207 1000000 loops, best of 3: 1.43 usec per loop
Senthil Kumaran2e015352011-08-06 13:37:04 +0800208 $ python -m timeit 'if hasattr(int, "__bool__"): pass'
Georg Brandl116aa622007-08-15 14:28:22 +0000209 100000 loops, best of 3: 2.23 usec per loop
210
211::
212
213 >>> import timeit
214 >>> s = """\
215 ... try:
216 ... str.__bool__
217 ... except AttributeError:
218 ... pass
219 ... """
220 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000221 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000222 17.09 usec/pass
223 >>> s = """\
224 ... if hasattr(str, '__bool__'): pass
225 ... """
226 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000227 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000228 4.85 usec/pass
229 >>> s = """\
230 ... try:
231 ... int.__bool__
232 ... except AttributeError:
233 ... pass
234 ... """
235 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000236 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000237 1.97 usec/pass
238 >>> s = """\
239 ... if hasattr(int, '__bool__'): pass
240 ... """
241 >>> t = timeit.Timer(stmt=s)
Collin Winterc79461b2007-09-01 23:34:30 +0000242 >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
Georg Brandl116aa622007-08-15 14:28:22 +0000243 3.15 usec/pass
244
245To give the :mod:`timeit` module access to functions you define, you can pass a
246``setup`` parameter which contains an import statement::
247
248 def test():
Senthil Kumaran2e015352011-08-06 13:37:04 +0800249 """Stupid test function"""
Collin Winterc79461b2007-09-01 23:34:30 +0000250 L = [i for i in range(100)]
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Senthil Kumaran2e015352011-08-06 13:37:04 +0800252 if __name__ == '__main__':
Georg Brandl116aa622007-08-15 14:28:22 +0000253 from timeit import Timer
254 t = Timer("test()", "from __main__ import test")
Collin Winterc79461b2007-09-01 23:34:30 +0000255 print(t.timeit())
Georg Brandl116aa622007-08-15 14:28:22 +0000256