26.6. timeit — Measure execution time of small code snippets¶
New in version 2.3:
New in version 2.3.
This module provides a simple way to time small bits of Python code. It has both command line as well as callable interfaces. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the Python Cookbook, published by O’Reilly.
The module defines the following public class:
-
class
timeit.Timer([stmt='pass'[, setup='pass'[, timer=<timer function>]]])¶ Class for timing execution speed of small code snippets.
The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to
'pass'; the timer function is platform-dependent (see the module doc string). stmt and setup may also contain multiple statements separated by;or newlines, as long as they don’t contain multi-line string literals.To measure the execution time of the first statement, use the
timeit()method. Therepeat()method is a convenience to calltimeit()multiple times and return a list of results.Changed in version 2.6:
Changed in version 2.6: The stmt and setup parameters can now also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by
timeit(). Note that the timing overhead is a little larger in this case because of the extra function calls.