data science

Timing Execution – Python

This is a simple function that can help you time the code.

All it does is use time() from the time module to saves the current time when the code begins, then saves the current time when it ends, and then calculates the difference.

Then it uses the gmtime and strtime to format the calculated time into a nice little HH:MM:SS format.

The function looks like this

from time import time, gmtime, strftime

def _time_now(time_START):

    # the difference between the time now and 
    # when you started counting
    time_LAPSE_SECONDS = time() - time_START

    # Change the format to something nicer to read
    time_LAPSE = strftime('%H:%M:%S'gmtime(time_LAPSE_SECONDS))

    return time_LAPSE

You can then run this code like so

# this is where you start counting
start_counting = time()

# then all your long and really cool complex code goes here.
# or the first section of it...
# so say you want to see how long this first bit takes to run..
# you do this.

print _time_now(start_counting)

# you can, if you want to, start a second timer here
start_counting_again = time()
# then the second bit of your code goes here.
# So now you can go and make some coffee,
# or just wait until the code is finally done...

# this bit will tell how long the last section took to run
print _time_now(start_counting_again)

# and finally this will tell you how long the entire code took
print _time_now(start_counting)

Note: This will only count to the nearest second, so if the code runs in milli seconds, you might as well just do

from time import time

time_START = time()

# lots and lots of code here

time_END = time()

time_LAPSE = time_END - time_START

print time_LAPSE

and that should print a float, like this one


which means the entire code took 0.1252 of a second to run.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s