Computer Studies‎ > ‎Python‎ > ‎Python Tutorial‎ > ‎

Determining Execution Time

The time to execute a program (or sub-program) can be determined by first storing the local time in a variable, executing your code, then subtracting the first time from the the final time.

The following snippets shows how to do this:

import time

t1 = time.clock()
num = 1
for n in range(1,5e6):
    num = num * 1 # this is meaningless, and only used as an example to waste time

print ("The elapsed time is", time.clock() - t1, "seconds")

The important function here is time.clock(), which returns a floating point number based on the "processor time", and typically has a resolution better than 1 microsecond.

Note: See http://docs.python.org/release/2.5.2/lib/module-time.html for other time functions.
Comments