Rough and ready timing using Python

When performing a Sysadmin or DevOps role, it’s inevitable that you’ll be writing up a script at some point to automate a task, such as running installers or retrieving files. One part of writing up a script, no matter how large, is that you’ll need to test it to make sure that everything is working as expected, which includes the time it takes for the script to run.

Python features a number of modules that have timing components within them, but most of them can be more hassle than they’re worth if you’re not too concerned with accuracy and just want to measure something to the second. The following code (as found here) makes use of Python’s time module to get you up and running with a crude timer.

Note: The code can give unexpected results, as explained later in this post. However, if you just want a really rough and quick time-elapsed notification, give this a try:

from time import time
 
if __name__ == '__main__':
 
    start = time()
 
    # do your thang
 
    elapsed = time() - start
    print("Complete!  Code duration was %s seconds." % elapsed)

The above code should be pretty self-explanatory. Import the time module, record your starting and current times, and compare the two to determine the time elapsed.

That said, the code brings about some unexpected results, as explained here. The problem lies in the unpredictability of the time module, such as in this piece of code I timed:

for x in range(0,1000000):
    print x

This returned me times (in seconds) of 15.1807610989, 15.5729680061, and 15.1461789608 respectively. Not too concerning for something so small, but when you’re getting such noticeable fluctuations now it’s not too much of a stretch to suggest that timing something larger will produce a greater fluctuation in results. Some people have recommended using time.clock() instead, as it’a generally more suited to benchmarking tasks than time.time() is.

Or if you want something really reliable, you could use a module called timeit, which can be called either within a python module or directly from the command line, and is known to produce more reliable results.