The hard part of timing code snippets accurately is that the operating system and other running processes get in the way. This makes micro-benchmarks hard to perform accurately, and the timeit module is designed for this purpose. But for more heavyweight code, the noise introduced by the OS is usually unimportant (although if your anti-virus scanner decides to schedule a full disk scan just as your test starts, your results may be affected...), and using timeit doesn't gain you very much and this is much more convenient.

This should work in any version of Python from 2.5 onwards. In 2.5, you will need to enable the with statement first:

from __future__ import with_statement

The Timer object takes three optional arguments: a timer function, a flag telling it whether or not to disable Python's garbage collector, and a verbose flag.

The usual choices for the timer function are time.clock (usually best for Windows) or time.time (usually best for other platforms). By default, it will use the platform-specific default timer from the timeit module.

If the second argument is true, the garbage collector will be disabled just before running the code block, and then reverted to its previous state afterwards. By default the garbage collector is left alone.

If the third argument is true, the benchmark is printed just after finishing. Note that if an exception takes place inside the block, the benchmark will still be printed just before the traceback.