Fixed a wrong apostrophe
[python.git] / Doc / library / timeit.rst
blob4f930b354fee688bc69244705de3ad5c9955f1fb
2 :mod:`timeit` --- Measure execution time of small code snippets
3 ===============================================================
5 .. module:: timeit
6    :synopsis: Measure the execution time of small code snippets.
9 .. versionadded:: 2.3
11 .. index::
12    single: Benchmarking
13    single: Performance
15 This module provides a simple way to time small bits of Python code. It has both
16 command line as well as callable interfaces.  It avoids a number of common traps
17 for measuring execution times.  See also Tim Peters' introduction to the
18 "Algorithms" chapter in the Python Cookbook, published by O'Reilly.
20 The module defines the following public class:
23 .. class:: Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])
25    Class for timing execution speed of small code snippets.
27    The constructor takes a statement to be timed, an additional statement used for
28    setup, and a timer function.  Both statements default to ``'pass'``; the timer
29    function is platform-dependent (see the module doc string).  *stmt* and *setup*
30    may also contain multiple statements separated by ``;`` or newlines, as long as
31    they don't contain multi-line string literals.
33    To measure the execution time of the first statement, use the :meth:`timeit`
34    method.  The :meth:`repeat` method is a convenience to call :meth:`timeit`
35    multiple times and return a list of results.
37    .. versionchanged:: 2.6
38       The *stmt* and *setup* parameters can now also take objects that are callable
39       without arguments. This will embed calls to them in a timer function that will
40       then be executed by :meth:`timeit`.  Note that the timing overhead is a little
41       larger in this case because of the extra function calls.
44 .. method:: Timer.print_exc([file=None])
46    Helper to print a traceback from the timed code.
48    Typical use::
50       t = Timer(...)       # outside the try/except
51       try:
52           t.timeit(...)    # or t.repeat(...)
53       except:
54           t.print_exc()
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``.
61 .. method:: Timer.repeat([repeat=3 [, number=1000000]])
63    Call :meth:`timeit` a few times.
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`.
70    .. note::
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.
82 .. method:: Timer.timeit([number=1000000])
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.
90    .. note::
92       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::
99          timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()
101 Starting with version 2.6, the module also defines two convenience functions:
104 .. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]])
106    Create a :class:`Timer` instance with the given statement, setup code and timer
107    function and run its :meth:`repeat` method with the given repeat count and
108    *number* executions.
110    .. versionadded:: 2.6
113 .. function:: timeit(stmt[, setup[, timer[, number=1000000]]])
115    Create a :class:`Timer` instance with the given statement, setup code and timer
116    function and run its :meth:`timeit` method with *number* executions.
118    .. versionadded:: 2.6
121 Command Line Interface
122 ----------------------
124 When called as a program from the command line, the following form is used::
126    python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
128 where the following options are understood:
130 -n N/:option:`--number=N`
131    how many times to execute 'statement'
133 -r N/:option:`--repeat=N`
134    how many times to repeat the timer (default 3)
136 -s S/:option:`--setup=S`
137    statement to be executed once initially (default ``'pass'``)
139 -t/:option:`--time`
140    use :func:`time.time` (default on all platforms but Windows)
142 -c/:option:`--clock`
143    use :func:`time.clock` (default on Windows)
145 -v/:option:`--verbose`
146    print raw timing results; repeat for more digits precision
148 -h/:option:`--help`
149    print a short usage message and exit
151 A multi-line statement may be given by specifying each line as a separate
152 statement argument; indented lines are possible by enclosing an argument in
153 quotes and using leading spaces.  Multiple :option:`-s` options are treated
154 similarly.
156 If :option:`-n` is not given, a suitable number of loops is calculated by trying
157 successive powers of 10 until the total time is at least 0.2 seconds.
159 The default timer function is platform dependent.  On Windows,
160 :func:`time.clock` has microsecond granularity but :func:`time.time`'s
161 granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a
162 second granularity and :func:`time.time` is much more precise.  On either
163 platform, the default timer functions measure wall clock time, not the CPU time.
164 This means that other processes running on the same computer may interfere with
165 the timing.  The best thing to do when accurate timing is necessary is to repeat
166 the timing a few times and use the best time.  The :option:`-r` option is good
167 for this; the default of 3 repetitions is probably enough in most cases.  On
168 Unix, you can use :func:`time.clock` to measure CPU time.
170 .. note::
172    There is a certain baseline overhead associated with executing a pass statement.
173    The code here doesn't try to hide it, but you should be aware of it.  The
174    baseline overhead can be measured by invoking the program without arguments.
176 The baseline overhead differs between Python versions!  Also, to fairly compare
177 older Python versions to Python 2.3, you may want to use Python's :option:`-O`
178 option for the older versions to avoid timing ``SET_LINENO`` instructions.
181 Examples
182 --------
184 Here are two example sessions (one using the command line, one using the module
185 interface) that compare the cost of using :func:`hasattr` vs.
186 :keyword:`try`/:keyword:`except` to test for missing and present object
187 attributes. ::
189    % timeit.py 'try:' '  str.__nonzero__' 'except AttributeError:' '  pass'
190    100000 loops, best of 3: 15.7 usec per loop
191    % timeit.py 'if hasattr(str, "__nonzero__"): pass'
192    100000 loops, best of 3: 4.26 usec per loop
193    % timeit.py 'try:' '  int.__nonzero__' 'except AttributeError:' '  pass'
194    1000000 loops, best of 3: 1.43 usec per loop
195    % timeit.py 'if hasattr(int, "__nonzero__"): pass'
196    100000 loops, best of 3: 2.23 usec per loop
200    >>> import timeit
201    >>> s = """\
202    ... try:
203    ...     str.__nonzero__
204    ... except AttributeError:
205    ...     pass
206    ... """
207    >>> t = timeit.Timer(stmt=s)
208    >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
209    17.09 usec/pass
210    >>> s = """\
211    ... if hasattr(str, '__nonzero__'): pass
212    ... """
213    >>> t = timeit.Timer(stmt=s)
214    >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
215    4.85 usec/pass
216    >>> s = """\
217    ... try:
218    ...     int.__nonzero__
219    ... except AttributeError:
220    ...     pass
221    ... """
222    >>> t = timeit.Timer(stmt=s)
223    >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
224    1.97 usec/pass
225    >>> s = """\
226    ... if hasattr(int, '__nonzero__'): pass
227    ... """
228    >>> t = timeit.Timer(stmt=s)
229    >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
230    3.15 usec/pass
232 To give the :mod:`timeit` module access to functions you define, you can pass a
233 ``setup`` parameter which contains an import statement::
235    def test():
236        "Stupid test function"
237        L = []
238        for i in range(100):
239            L.append(i)
241    if __name__=='__main__':
242        from timeit import Timer
243        t = Timer("test()", "from __main__ import test")
244        print t.timeit()