Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

time

Is there a simple way to time a Python program's execution?

clarification: Entire programs

like image 387
MyNameIsKhan Avatar asked Jun 04 '12 14:06

MyNameIsKhan


People also ask

How do you time how long a Python script takes?

The first method to find the execution time of a Python script is via the time() method of the time module. Basically, you need to call the time() method before the code starts. The time() method of the time module returns the current system time.

What does time time () do in Python?

time() The time() function returns the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).

Which module can say how long your code took to run Python?

This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

How do I find the runtime of a program?

Using clock() function We can use the clock() function provided by the <time. h> header file to calculate the CPU time consumed by a task within a C application. It returns the clock_t type, which stores the total number of clock ticks.


2 Answers

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
like image 98
Martijn Pieters Avatar answered Sep 19 '22 21:09

Martijn Pieters


You might want to use built-in profiler.

Also you might want to measure function's running time by using following simple decorator:

import time
def myprof(func):
    def wrapping_fun(*args):
        start = time.clock()
        result = func(*args)
        end = time.clock()
        print 'Run time of %s is %4.2fs' % (func.__name__, (end - start))
        return result
    return wrapping_fun

Usage:

@myprof
def myfun():
    # function body 
like image 35
cval Avatar answered Sep 20 '22 21:09

cval