In Python you can write different pieces of codes to perform the same task. However, writing an efficient code, which consumes less CPU cycles and is light on memory, is crucial for production-grade applications. A poorly written code can make your application take longer to respond to user inputs. There are several ways to measure code quality, like finding the time complexity via big o notation and calculating the memory occupied by the code. One of the ways to measure the code quality is to calculate the time it takes to complete its execution. In this article, you’ll see different ways to measure the execution time of a Python script.

There are three main methods to find the execution time of a Python script:

  1. Using the time module
  2. Using the timeit module
  3. Using the %%time command (Only in Jupyter Notebook)

To test these three methods, we’ll write two functions that calculate the factorial of a number passed to it as a parameter.

In the script below, the cal_fact() function uses recursive calls to calculate the factorial of a number.

def cal_fact(n):
    if n == 1:
        return n
    else:
        return n * cal_fact(n-1)

In our next script, we define another function cal_fact2() which uses simple iterations to calculate the factorial of a number passed to it as a parameter value.

def cal_fact2(n):
    if n == 1:
        return n
    else:
        result = 1
        for i in range(2,n+1):
            result = result * i
        return result

We’re going to use these two functions in the next sections, where we’ll exercise the three methods for finding the execution times. Though both the functions perform the same task, you’ll see that their execution times will differ.

Finding the Execution Time using Python time Module

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. Next, you call the time() method again after the code completes execution. Finally, you subtract the time value calculated before the start of the code from the time value calculated after the code completes execution. That’s simple enough, right?

The following script calculates the execution time for the cal_fact() function for calculating the factorial of 2500.

# import the builtin time module
import time

# Grab Currrent Time Before Running the Code
start = time.time()

cal_fact(2500)

# Grab Currrent Time After Running the Code
end = time.time()

#Subtract Start Time from The End Time
total_time = end - start
print("\n"+ str(total_time))

Output:

0.004949808120727539

NOTE: If you get a RecursionError: maximum recursion depth exceeded in comparison, you may need to reduce the 2500 to a number less than 1020.

The output shows that the system took 0.00494 seconds to execute the cal_fact() function for calculating the factorial of 2500. That’s pretty fast!

Similarly, the following script calculates the execution time of the cal_fact2() function when a parameter value of 2500 is passed to it.

# import the builtin time module
import time

# Grab Currrent Time Before Running the Code
start = time.time()

cal_fact2(2500)

# Grab Currrent Time After Running the Code
end = time.time()

#Subtract Start Time from The End Time
total_time = end - start
print("\n"+ str(total_time))

Output:

0.0019457340240478516

The output shows that cal_fact2() was even faster, taking only 0.00194 seconds to find the factorial of 2500.

The time module is useful when you want to calculate the execution time of large scripts. If the execution time of a particular piece of code is a tiny fraction of second, the time module will return 0.0 because the time taken by a code to complete its execution is too insignificant to be measured using the time() method.

Let’s see an example. Instead of calculating factorial of 2500, lets find the factorial of a smaller number, 100, using the cal_fact() method. Run the following script.

# import the builtin time module
import time

# Grab Currrent Time Before Running the Code
start = time.time()

cal_fact(100)

# Grab Currrent Time After Running the Code
end = time.time()

#Subtract Start Time from The End Time
total_time = end - start
print("\n"+ str(total_time))

Output:

0.0

The output returns 0.0. Though the code actually took some time to execute, the time() function could not measure it because the difference between the time before and after the execution of the cal_fact() function is too insignificant.

Similarly, you can run the cal_fact2() function to calculate the factorial of 100, and you’ll again see that the execution time is 0.0.

When the execution time of a code is too insignificant to be measured, you can use the Python timeit module. instead.


Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit

Finding the Execution Time using Python timeit Module

The timeit module in Python is a default Python module whose sole job is to calculate the execution time of a Python script. The following script imports the timeit module.

import timeit

To find the execution time of a code using the timeit module, you need to pass the call to the function that you want to execute, as a first parameter value to the timeit() fuction. The function call should be passed in a string format. The second parameter value is the function that is to be executed. The third parameter is the number of iterations for the execution of the function.

In the following script, you pass the function call in the form of a multiline string to the statement variable. The function body for the cal_func() is passed to the setup variable.

statement = '''
cal_fact(100)
'''

setup = '''
def cal_fact(n):
    if n == 1:
        return n
    else:
        return n * cal_fact(n-1)
'''

Finally, the statement and setup variables are passed to the timeit() function of the timeit module. The function is executed for a million times.

print(timeit.timeit(statement, setup, number = 1000000))

Output:

23.135807499999828

The output shows that, it takes 23.13 seconds to run the cal_func() function a million times to find the factorial of 100.

Let’s now find the factorial of 100, with 1 million iterations, using the cal_fact2() function. We’ll again make use of the timeit() function.

statement2 = '''
cal_fact2(100)
'''

setup2 = '''
def cal_fact2(n):
    if n == 1:
        return n
    else:
        result = 1
        for i in range(2,n+1):
            result = result * i
        return result
'''
print(timeit.timeit(statement2, setup2, number = 1000000))

Output:

10.493902499999876

The output shows that the cal_fact2() method took 10.49 seconds, which shows that the cal_fact2() is about twice as fast as the cal_fact() function.

Finding the Execution Time using Python %%time command

If you run your code in the Jupyter Notebook, you have a third option for calculating how long it takes your Python code to run. Simply add the %%timeit command in the Jupyter Notebook cell that contains your code. The %%timeit command should be the first command in a cell. For instance, the following script measures the execution time of the cal_fact() function for calculating the factorial of 100.

%%timeit
cal_fact(100)

Output:

18.4 µs ± 1.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

The output shows that the code took an average of 18.4 microsecond to run. By default, %%timeit module runs your python script one hundred thousand times to determine its run time.

Similarly, you can calculate the execution time for cal_fact2() function as follows:

%%timeit
cal_fact2(100)

Output:

10.5 µs ± 3.51 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The cal_fact2() function took 10.5 microseconds to calculate the factorial of 100, though it had a bit higher standard deviation. Still, the %%timeit technique confirms that cal_fact2() is much faster than our recursive cal_fact() function.


Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit