How to measure the execution time of a Python script 1


Have you ever had more than two pieces of code that do the same thing and you don’t know which one is better?

Well, if you find yourself in that scenario just go ahead and measure the execution time of each script and then pick the script that executes faster. The faster the execution time the better the user experience will be.

The way to measure the script execution time is by using the time built-in Python module. Simply edit your .py file and insert two lines on top and two lines at the bottom as shown below:

import time
start = time.time()

"the code you want to test stays here"

end = time.time()
print(end - start)

Executing that code will print out the time in seconds that it took for the script to execute.

Let’s look at an example.

Let’s assume your duty is to generate a list where each item is a product of the multiplication of the items of another list by two. You can either use a for loop or a list comprehension. Here is how you would check the time of each of the scripts:

Using a for loop:

 

import time
start = time.time()

a = range(100000)
b = []
for i in a:
    b.append(i*2)

end = time.time()
print(end - start)

That would output 0.02017498016357422 seconds on my computer. So, the script took around 2/100 of a second to execute.

Let’s now try to build the same list, but instead of using a for loop we will use a list comprehension:

 

import time
start = time.time()

a = range(100000)
b = [i*2 for i in a]

end = time.time()
print(end - start)

That would output 0.009402990341186523 which means two times faster than the for loop. Quite a difference!

Something important to note is that your computer may display different values depending on your processor capabilities and how busy your processor is with other tasks at the time you execute the Python script. The values above come from a laptop with a 2.6 GHz i7 processor. However, the ratio between the two scripts should be similar among different computers.

That’s how easy it is to measure the “speed” of a Python script.

Talk to you next time!

Ardit


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “How to measure the execution time of a Python script