Open In App

How to check the execution time of Python script ?

In this article, we will discuss how to check the execution time of a Python script.

There are many Python modules like time, timeit and datetime module in Python which can store the time at which a particular section of the program is being executed. By manipulating or getting the difference between times of beginning and ending at which a particular section is being executed, we can calculate the time it took to execute the section. 



The following methods can be used to compute time difference:

Using the time module check the execution time of Python 

Example 1: Measuring time taken for a code segment by recording start and end times

Computing the time using the time module and time.time() function. We have computed the time of the above program, which came out of the order 10^-3. We can check for the time by increasing the number of computations using the same algorithms.






# Import time module
import time
 
# record start time
start = time.time()
 
# define a sample code segment
a = 0
for i in range(1000):
    a += (i**100)
 
# record end time
end = time.time()
 
# print the difference between start
# and end time in milli. secs
print("The time of execution of above program is :",
      (end-start) * 10**3, "ms")

Output:

The time of execution of above program is : 0.77056884765625 ms

Example 2: Measuring time taken for a code segment by adding up the time required per iteration

Checking times for execution of the program for different numbers of computations. We see a general trend in the increase in time of computation for an increase in the number of execution. However, it may not show any linear trend or fixed increments.




# import time module
import time
 
# create sample code for testing
for j in range(100, 5501, 100):
    # store iteration start timestamp
    start = time.time()
    a = 0
    for i in range(j):
        a += (i**100)
    # store iteration end timestamp
    end = time.time()
 
    # show time of execution per iteration
    print(f"Iteration: {j}\tTime taken: {(end-start)*10**3:.03f}ms")

Output:

Iteration: 100    Time taken: 0.105ms
Iteration: 200    Time taken: 0.191ms
Iteration: 300    Time taken: 0.291ms
Iteration: 400    Time taken: 0.398ms
Iteration: 500    Time taken: 0.504ms
Iteration: 600    Time taken: 0.613ms
Iteration: 700    Time taken: 0.791ms
...
Iteration: 5400    Time taken: 6.504ms
Iteration: 5500    Time taken: 6.630ms

Explanation: Here we have truncated the output for representation purpose. But if we compare the iterations from 100 to 700 they are less than 1ms. But towards the end of the loop, each iteration taking ~7ms. Thus, there is an increase in time taken as the number of iterations have increased. This is generally because, the inner loop iterate more number of time depending on each outer iteration.

Using the DateTime module check the execution time

Using the datetime module in Python and datetime.now() function to record timestamp of start and end instance and finding the difference to get the code execution time.




from datetime import datetime
 
# record current timestamp
start = datetime.now()
 
# create loop-setup for testing
a = 0
for i in range(1000):
    a += (i**100)
 
# record loop end timestamp
end = datetime.now()
 
# find difference loop start and end time and display
td = (end - start).total_seconds() * 10**3
print(f"The time of execution of above program is : {td:.03f}ms")

Output:

The time of execution of above program is : 0.766ms

Using timeit module check the execution time

This would give us the execution time of any program. This module provides a simple way to find the execution time of small bits of Python code. It provides the timeit() method to do the same. The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments:

Example 1: Using timeit inside Python code snippet to measure execution time




# importing the required module
import timeit
 
# code snippet to be executed only once
# before the stmt parameter in timeit
mysetup = "from math import sqrt"
 
# code snippet whose execution time
# is to be measured
mycode = '''
def example():
    mylist = []
    for x in range(100):
        mylist.append(sqrt(x))
'''
 
# timeit statement
exec_time = timeit.timeit(stmt=mycode,
                          setup=mysetup,
                          number=1000000) * 10**3
print(f"The time of execution of above program is : {exec_time:.03f}ms")

Output:

The time of execution of above program is : 71.161ms

Example 2: Using timeit from command line to measure execution time

We can measure time taken by simple code statements without the need to write new Python files, using timeit CLI interface.

timeit supports various command line inputs, Here we will note a few of the mos common arguments:

timeit CLI statement:

python -m timeit -s "import random" "l = [x**9 for x in range(random.randint(1000, 1500))]"

Output:

500 loops, best of 5: 503 used per loop

Article Tags :