Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to check the execution time of Python script ?

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:

  • Python time module provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of the Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform-dependent.
  • Python datetime module defines a function that can be primarily used to get the current time and date. now() function Return the current local date and time, which is defined under the datetime module.
  • Python timeit module runs your snippet of code n number of times (the default value is, 1000000) so that you get the statistically most relevant measurement of code execution time.

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.

Python3




# 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.

Python3




# 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.

Python3




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:

  • stmt which is the statement you want to measure; it defaults to ‘pass’.
  • setup, which is the code that you run before running the stmt; it defaults to ‘pass’. We generally use this to import the required modules for our code.
  • timer, which is a timeit.Timer object; usually has a sensible default value, so you don’t have to worry about it.
  • The number, which is the number of executions you’d like to run the stmt.

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

Python3




# 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:

  • -s [–setup]: Setup code to run before running the code statement.
  • -n [–number]: Number of times to execute the statement.
  • p [–process]: Measure the process time of the code execution, instead of the wall-clock time.
  • Statement: The code statements to test the execution time, taken as a positional argument.

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

RELATED ARTICLES

Most Popular

Recent Comments