Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes
timeit.Timer Class Reference

List of all members.

Public Member Functions

def __init__
def print_exc
def timeit
def repeat

Public Attributes

 timer
 src
 inner

Detailed Description

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
module doc string).

To measure the execution time of the first statement, use the
timeit() method.  The repeat() method is a convenience to call
timeit() multiple times and return a list of results.

The statements may contain newlines, as long as they don't contain
multi-line string literals.

Definition at line 105 of file timeit.py.


Constructor & Destructor Documentation

def timeit.Timer.__init__ (   self,
  stmt = "pass",
  setup = "pass",
  timer = default_timer 
)
Constructor.  See class doc string.

Definition at line 121 of file timeit.py.

00121 
00122     def __init__(self, stmt="pass", setup="pass", timer=default_timer):
00123         """Constructor.  See class doc string."""
00124         self.timer = timer
00125         ns = {}
00126         if isinstance(stmt, str):
00127             stmt = reindent(stmt, 8)
00128             if isinstance(setup, str):
00129                 setup = reindent(setup, 4)
00130                 src = template % {'stmt': stmt, 'setup': setup}
00131             elif hasattr(setup, '__call__'):
00132                 src = template % {'stmt': stmt, 'setup': '_setup()'}
00133                 ns['_setup'] = setup
00134             else:
00135                 raise ValueError("setup is neither a string nor callable")
00136             self.src = src # Save for traceback display
00137             code = compile(src, dummy_src_name, "exec")
00138             exec(code, globals(), ns)
00139             self.inner = ns["inner"]
00140         elif hasattr(stmt, '__call__'):
00141             self.src = None
00142             if isinstance(setup, str):
00143                 _setup = setup
00144                 def setup():
00145                     exec(_setup, globals(), ns)
00146             elif not hasattr(setup, '__call__'):
00147                 raise ValueError("setup is neither a string nor callable")
00148             self.inner = _template_func(setup, stmt)
00149         else:
00150             raise ValueError("stmt is neither a string nor callable")

Here is the caller graph for this function:


Member Function Documentation

def timeit.Timer.print_exc (   self,
  file = None 
)
Helper to print a traceback from the timed code.

Typical use:

    t = Timer(...)       # outside the try/except
    try:
t.timeit(...)    # or t.repeat(...)
    except:
t.print_exc()

The advantage over the standard traceback is that source lines
in the compiled template will be displayed.

The optional file argument directs where the traceback is
sent; it defaults to sys.stderr.

Definition at line 151 of file timeit.py.

00151 
00152     def print_exc(self, file=None):
00153         """Helper to print a traceback from the timed code.
00154 
00155         Typical use:
00156 
00157             t = Timer(...)       # outside the try/except
00158             try:
00159                 t.timeit(...)    # or t.repeat(...)
00160             except:
00161                 t.print_exc()
00162 
00163         The advantage over the standard traceback is that source lines
00164         in the compiled template will be displayed.
00165 
00166         The optional file argument directs where the traceback is
00167         sent; it defaults to sys.stderr.
00168         """
00169         import linecache, traceback
00170         if self.src is not None:
00171             linecache.cache[dummy_src_name] = (len(self.src),
00172                                                None,
00173                                                self.src.split("\n"),
00174                                                dummy_src_name)
00175         # else the source is already stored somewhere else
00176 
00177         traceback.print_exc(file=file)

Here is the call graph for this function:

def timeit.Timer.repeat (   self,
  repeat = default_repeat,
  number = default_number 
)
Call timeit() a few times.

This is a convenience function that calls the timeit()
repeatedly, returning a list of results.  The first argument
specifies how many times to call timeit(), defaulting to 3;
the second argument specifies the timer argument, defaulting
to one million.

Note: it's tempting to calculate mean and standard deviation
from the result vector and report these.  However, this is not
very useful.  In a typical case, the lowest value gives a
lower bound for how fast your machine can run the given code
snippet; higher values in the result vector are typically not
caused by variability in Python's speed, but by other
processes interfering with your timing accuracy.  So the min()
of the result is probably the only number you should be
interested in.  After that, you should look at the entire
vector and apply common sense rather than statistics.

Definition at line 201 of file timeit.py.

00201 
00202     def repeat(self, repeat=default_repeat, number=default_number):
00203         """Call timeit() a few times.
00204 
00205         This is a convenience function that calls the timeit()
00206         repeatedly, returning a list of results.  The first argument
00207         specifies how many times to call timeit(), defaulting to 3;
00208         the second argument specifies the timer argument, defaulting
00209         to one million.
00210 
00211         Note: it's tempting to calculate mean and standard deviation
00212         from the result vector and report these.  However, this is not
00213         very useful.  In a typical case, the lowest value gives a
00214         lower bound for how fast your machine can run the given code
00215         snippet; higher values in the result vector are typically not
00216         caused by variability in Python's speed, but by other
00217         processes interfering with your timing accuracy.  So the min()
00218         of the result is probably the only number you should be
00219         interested in.  After that, you should look at the entire
00220         vector and apply common sense rather than statistics.
00221         """
00222         r = []
00223         for i in range(repeat):
00224             t = self.timeit(number)
00225             r.append(t)
00226         return r

Here is the call graph for this function:

def timeit.Timer.timeit (   self,
  number = default_number 
)
Time 'number' executions of the main statement.

To be precise, this executes the setup statement once, and
then returns the time it takes to execute the main statement
a number of times, as a float measured in seconds.  The
argument is the number of times through the loop, defaulting
to one million.  The main statement, the setup statement and
the timer function to be used are passed to the constructor.

Definition at line 178 of file timeit.py.

00178 
00179     def timeit(self, number=default_number):
00180         """Time 'number' executions of the main statement.
00181 
00182         To be precise, this executes the setup statement once, and
00183         then returns the time it takes to execute the main statement
00184         a number of times, as a float measured in seconds.  The
00185         argument is the number of times through the loop, defaulting
00186         to one million.  The main statement, the setup statement and
00187         the timer function to be used are passed to the constructor.
00188         """
00189         if itertools:
00190             it = itertools.repeat(None, number)
00191         else:
00192             it = [None] * number
00193         gcold = gc.isenabled()
00194         gc.disable()
00195         try:
00196             timing = self.inner(it, self.timer)
00197         finally:
00198             if gcold:
00199                 gc.enable()
00200         return timing

Here is the caller graph for this function:


Member Data Documentation

Definition at line 138 of file timeit.py.

Definition at line 135 of file timeit.py.

Definition at line 123 of file timeit.py.


The documentation for this class was generated from the following file: