/Doc/library/timeit.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 244 lines · 176 code · 68 blank · 0 comment · 0 complexity · 3a913ce1e814d45eace5a00b4105b489 MD5 · raw file

  1. :mod:`timeit` --- Measure execution time of small code snippets
  2. ===============================================================
  3. .. module:: timeit
  4. :synopsis: Measure the execution time of small code snippets.
  5. .. versionadded:: 2.3
  6. .. index::
  7. single: Benchmarking
  8. single: Performance
  9. This module provides a simple way to time small bits of Python code. It has both
  10. command line as well as callable interfaces. It avoids a number of common traps
  11. for measuring execution times. See also Tim Peters' introduction to the
  12. "Algorithms" chapter in the Python Cookbook, published by O'Reilly.
  13. The module defines the following public class:
  14. .. class:: Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])
  15. Class for timing execution speed of small code snippets.
  16. The constructor takes a statement to be timed, an additional statement used for
  17. setup, and a timer function. Both statements default to ``'pass'``; the timer
  18. function is platform-dependent (see the module doc string). The statements may
  19. contain newlines, as long as they don't contain multi-line string literals.
  20. To measure the execution time of the first statement, use the :meth:`timeit`
  21. method. The :meth:`repeat` method is a convenience to call :meth:`timeit`
  22. multiple times and return a list of results.
  23. .. versionchanged:: 2.6
  24. The *stmt* and *setup* parameters can now also take objects that are callable
  25. without arguments. This will embed calls to them in a timer function that will
  26. then be executed by :meth:`timeit`. Note that the timing overhead is a little
  27. larger in this case because of the extra function calls.
  28. .. method:: Timer.print_exc([file=None])
  29. Helper to print a traceback from the timed code.
  30. Typical use::
  31. t = Timer(...) # outside the try/except
  32. try:
  33. t.timeit(...) # or t.repeat(...)
  34. except:
  35. t.print_exc()
  36. The advantage over the standard traceback is that source lines in the compiled
  37. template will be displayed. The optional *file* argument directs where the
  38. traceback is sent; it defaults to ``sys.stderr``.
  39. .. method:: Timer.repeat([repeat=3 [, number=1000000]])
  40. Call :meth:`timeit` a few times.
  41. This is a convenience function that calls the :meth:`timeit` repeatedly,
  42. returning a list of results. The first argument specifies how many times to
  43. call :meth:`timeit`. The second argument specifies the *number* argument for
  44. :func:`timeit`.
  45. .. note::
  46. It's tempting to calculate mean and standard deviation from the result vector
  47. and report these. However, this is not very useful. In a typical case, the
  48. lowest value gives a lower bound for how fast your machine can run the given
  49. code snippet; higher values in the result vector are typically not caused by
  50. variability in Python's speed, but by other processes interfering with your
  51. timing accuracy. So the :func:`min` of the result is probably the only number
  52. you should be interested in. After that, you should look at the entire vector
  53. and apply common sense rather than statistics.
  54. .. method:: Timer.timeit([number=1000000])
  55. Time *number* executions of the main statement. This executes the setup
  56. statement once, and then returns the time it takes to execute the main statement
  57. a number of times, measured in seconds as a float. The argument is the number
  58. of times through the loop, defaulting to one million. The main statement, the
  59. setup statement and the timer function to be used are passed to the constructor.
  60. .. note::
  61. By default, :meth:`timeit` temporarily turns off :term:`garbage collection`
  62. during the timing. The advantage of this approach is that it makes
  63. independent timings more comparable. This disadvantage is that GC may be
  64. an important component of the performance of the function being measured.
  65. If so, GC can be re-enabled as the first statement in the *setup* string.
  66. For example::
  67. timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()
  68. Starting with version 2.6, the module also defines two convenience functions:
  69. .. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]])
  70. Create a :class:`Timer` instance with the given statement, setup code and timer
  71. function and run its :meth:`repeat` method with the given repeat count and
  72. *number* executions.
  73. .. versionadded:: 2.6
  74. .. function:: timeit(stmt[, setup[, timer[, number=1000000]]])
  75. Create a :class:`Timer` instance with the given statement, setup code and timer
  76. function and run its :meth:`timeit` method with *number* executions.
  77. .. versionadded:: 2.6
  78. Command Line Interface
  79. ----------------------
  80. When called as a program from the command line, the following form is used::
  81. python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
  82. where the following options are understood:
  83. -n N/:option:`--number=N`
  84. how many times to execute 'statement'
  85. -r N/:option:`--repeat=N`
  86. how many times to repeat the timer (default 3)
  87. -s S/:option:`--setup=S`
  88. statement to be executed once initially (default ``'pass'``)
  89. -t/:option:`--time`
  90. use :func:`time.time` (default on all platforms but Windows)
  91. -c/:option:`--clock`
  92. use :func:`time.clock` (default on Windows)
  93. -v/:option:`--verbose`
  94. print raw timing results; repeat for more digits precision
  95. -h/:option:`--help`
  96. print a short usage message and exit
  97. A multi-line statement may be given by specifying each line as a separate
  98. statement argument; indented lines are possible by enclosing an argument in
  99. quotes and using leading spaces. Multiple :option:`-s` options are treated
  100. similarly.
  101. If :option:`-n` is not given, a suitable number of loops is calculated by trying
  102. successive powers of 10 until the total time is at least 0.2 seconds.
  103. The default timer function is platform dependent. On Windows,
  104. :func:`time.clock` has microsecond granularity but :func:`time.time`'s
  105. granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of a
  106. second granularity and :func:`time.time` is much more precise. On either
  107. platform, the default timer functions measure wall clock time, not the CPU time.
  108. This means that other processes running on the same computer may interfere with
  109. the timing. The best thing to do when accurate timing is necessary is to repeat
  110. the timing a few times and use the best time. The :option:`-r` option is good
  111. for this; the default of 3 repetitions is probably enough in most cases. On
  112. Unix, you can use :func:`time.clock` to measure CPU time.
  113. .. note::
  114. There is a certain baseline overhead associated with executing a pass statement.
  115. The code here doesn't try to hide it, but you should be aware of it. The
  116. baseline overhead can be measured by invoking the program without arguments.
  117. The baseline overhead differs between Python versions! Also, to fairly compare
  118. older Python versions to Python 2.3, you may want to use Python's :option:`-O`
  119. option for the older versions to avoid timing ``SET_LINENO`` instructions.
  120. Examples
  121. --------
  122. Here are two example sessions (one using the command line, one using the module
  123. interface) that compare the cost of using :func:`hasattr` vs.
  124. :keyword:`try`/:keyword:`except` to test for missing and present object
  125. attributes. ::
  126. % timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
  127. 100000 loops, best of 3: 15.7 usec per loop
  128. % timeit.py 'if hasattr(str, "__nonzero__"): pass'
  129. 100000 loops, best of 3: 4.26 usec per loop
  130. % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
  131. 1000000 loops, best of 3: 1.43 usec per loop
  132. % timeit.py 'if hasattr(int, "__nonzero__"): pass'
  133. 100000 loops, best of 3: 2.23 usec per loop
  134. ::
  135. >>> import timeit
  136. >>> s = """\
  137. ... try:
  138. ... str.__nonzero__
  139. ... except AttributeError:
  140. ... pass
  141. ... """
  142. >>> t = timeit.Timer(stmt=s)
  143. >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
  144. 17.09 usec/pass
  145. >>> s = """\
  146. ... if hasattr(str, '__nonzero__'): pass
  147. ... """
  148. >>> t = timeit.Timer(stmt=s)
  149. >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
  150. 4.85 usec/pass
  151. >>> s = """\
  152. ... try:
  153. ... int.__nonzero__
  154. ... except AttributeError:
  155. ... pass
  156. ... """
  157. >>> t = timeit.Timer(stmt=s)
  158. >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
  159. 1.97 usec/pass
  160. >>> s = """\
  161. ... if hasattr(int, '__nonzero__'): pass
  162. ... """
  163. >>> t = timeit.Timer(stmt=s)
  164. >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
  165. 3.15 usec/pass
  166. To give the :mod:`timeit` module access to functions you define, you can pass a
  167. ``setup`` parameter which contains an import statement::
  168. def test():
  169. "Stupid test function"
  170. L = []
  171. for i in range(100):
  172. L.append(i)
  173. if __name__=='__main__':
  174. from timeit import Timer
  175. t = Timer("test()", "from __main__ import test")
  176. print t.timeit()