How to time how long a Python program takes to run?

python, time

Solution

Use `timeit`:

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.

You'll need a python statement in a string; if you have a main function in your code, you could use it like this:

>>> from timeit import Timer
>>> timer = Timer('main()', 'from yourmodule import main')
>>> print timer.timeit()

The second string provides the setup, the environment for the first statement to be timed in. The second part is not being timed, and is intended for setting the stage as it were. The first string is then run through it's paces; by default a million times, to get accurate timings.

If you need more detail as to where things are slow, use one of the `python profilers`:

A profiler is a program that describes the run time performance of a program, providing a variety of statistics.

The easiest way to run this is by using the `cProfile` module from the command line:

$ python -m cProfile yourprogram.py

Problem

Is there a simple way to time a Python program's execution? clarification: Entire programs

Original source