Skip to content
Related Articles

Related Articles

Improve Article

How to measure elapsed time in Python?

  • Last Updated : 26 Mar, 2021

In Python, we have three modules that help us find the execution time of a program. We would explore each of these in this article and also some of its functions that might help us to execute the programs. The modules we would be using are timeit, time, and Datetime. We are going to find out the elapsed time(the time is taken for the program to execute) in this article. 

Using Timeit Module

Python timeit module is often used to measure the execution time of small code snippets. We can also use the timeit() function which executes an anonymous function with a number of executions. It temporarily turns off garbage collection (the process of collecting unwanted variables whose use has been over and clears them by marking them as garbage values to free up the memory) during calculating the time of execution.  

In the first example, we would analyze how to use the timeit module and use it to find the execution time of a lambda expression. The code starts with importing the time module, and then we use the. The timeit() module to find the time required for executing the function. Finally, we print the result on the screen.

Python3




# importing the module
import timeit
  
  
# using the timeit method and lambda 
# expression to get the execution time of
# the function.
t = timeit.timeit(lambda: "print('Hello World!')")
  
# printing the execution time
print(t)

Output:



0.0777151

Now we would check how to use the timeit.timeit() function to get the execution time of a function. The function starts with importing the modules, then we create a sample function whose execution time we wish to calculate. Then we use the timeit.timeit() function and call the function inside the function as a parameter, and the next parameter is the number that defines how many times we execute this function.  Then we print the elapsed or execution time in the next line.

Python3




# importing the module
import timeit
  
# sample function that returns square
# of the value passed
def print_square(x):
    return (x**2)
  
# using the timeit method and lambda
# expression to get the execution time of
# the function, number defines how many
# times we execute this function
t = timeit.timeit(lambda: print_square(3), number=10)
  
# printing the execution time
print(t)

Output:

5.299999999999749e-06

Now, practically to estimate the execution time of a program we generally do not use the value obtained once as the ultimate correct value, because the execution of a program may depend upon os and availability of hardware at a particular instant of time. So generally we take multiple values of execution time and generally the average computed gives us the best possible answer. For this, we would use the timeit.repeat() method instead of timeit.timeit() which takes a repeat parameter and saves you the trouble of creating a loop and storing the values in the array.

Python3




# importing the module
import timeit
  
  
# sample function that returns square
# of the value passed
def print_square(x):
    return (x**2)
  
# using the repeat method and lambda
# expression to get the execution time of
# the function, number defines how many
# times we execute this function and the
# repeat defines the number of times the
# time calculation needs to be done.
t = timeit.repeat(lambda: print_square(3), number=10, repeat=5)
  
# printing the execution time
print(t)

Output:

[5.800000000000249e-06, 3.299999999997749e-06, 3.2000000000018125e-06, 3.1999999999948736e-06, 

3.4000000000006247e-06]



Also, we can use the timeit.default_timer() which basically records the time at the instant when the method is called. So we call the method just before and after the lines of the code for which we want to calculate the execution time and then basically the difference between the two times give us the result. So for finding the time we record the times using the timeit.defaultTimer() method, and then we print the difference between the two times in the last line. 

Python3




# importing the module
import timeit
  
  
# sample function that returns 
# square of the value passed
def print_square(x):
    return (x**2)
  
# records the time at this instant
# of the program
start = timeit.default_timer()
  
# calls the function
print_square(3)
  
# records the time at this instant 
# of the program
end = timeit.default_timer()
  
# printing the execution time by subtracting
# the time before the function from
# the time after the function
print(end-start)

Output:

2.299999999996749e-06

Using Time Module

We can use the time.perf_counter() method in the same way as the timeit.default_timer() method discussed above. It can use the highest possible resolution clock and gives you the most accurate result. In fact the timeit.default_timer() also uses time.perf_counter() as it’s base. This also records the time before and after the required lines of code whose execution or elapsed time needs to be calculated. Then we subtract the recorded time before the start of the lines from the recorded time after the lines of the code. 

Python3




# importing the module
import time
  
# sample function that returns square
# of the value passed
def print_square(x):
    return (x**2)
  
# records the time at this instant of the 
# program
start = time.perf_counter()
  
# calls the function
print_square(3)
  
# records the time at this instant of the
# program
end = time.perf_counter()
  
# printing the execution time by subtracting
# the time before the function from
# the time after the function
print(end-start)

Output:

2.299999999996749e-06

To measure the elapsed time or execution time of a block of code in nanoseconds, we can use the time.time_ns() function. This follows the same syntax as the time.perf_counter() function, like recording the time before and after the lines of the code and then subtracting the values and then printing them to the screen, but it records in nanoseconds instead of seconds.

Python3




# importing the module
import time
  
# sample function that returns square 
# of the value passed
def print_square(x):
    return (x**2)
  
# records the time in nanoseceonds at
# this instant of the program
start = time.time_ns()
  
# calls the function
print_square(3)
  
# records the time in nanoseceonds at this
# instant of the program
end = time.time_ns()
  
# printing the execution time by subtracting 
# the time before the function from
# the time after the function
print(end-start)

Output:

0

Note: Since my computer is having a fairly good processor and ram, it took 0 nanoseconds in my case. But it depends on your system how much time it takes for you to execute the function code.

Using Datetime Module

Datetime module can also be used to find the time elapsed or spent in a code block provided you are not looking for high precision. the datetime.now() also works the same way as the timeit.default_timer() or time.perf_counter() but lacks the same precision as those. It returns the result in HH:MM:SS format. This function is generally used for getting the current time and not a preferred use case for calculating execution time. However, these can be programs that take quite some time to execute like training ML/AI models, web scraping large websites, etc.   

Python3




# importing the module
from datetime import datetime
  
# sample function that returns square 
# of the value passed
def print_square(x):
    return (x**2)
  
# records the time at this instant of
# the program in HH:MM:SS format
start = datetime.now()
  
# calls the function
print_square(3)
  
# records the time at this instant of the
# program in HH:MM:SS format
end = datetime.now()
  
# printing the execution time by subtracting
# the time before the function from
# the time after the function
print(end-start)

Output:

0:00:00

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :