How to measure elapsed time in Python?

07 Jul, 2022
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 cover Python Program to Measure the Elapsed Time in Python.
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 moduleimport 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 timeprint(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 moduleimport timeit # sample function that returns square# of the value passeddef 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 functiont = timeit.timeit(lambda: print_square(3), number=10) # printing the execution timeprint(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 moduleimport timeit  # sample function that returns square# of the value passeddef 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 timeprint(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 moduleimport timeit  # sample function that returns# square of the value passeddef print_square(x):    return (x**2) # records the time at this instant# of the programstart = timeit.default_timer() # calls the functionprint_square(3) # records the time at this instant# of the programend = timeit.default_timer() # printing the execution time by subtracting# the time before the function from# the time after the functionprint(end-start)
Output:
2.299999999996749e-06
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 moduleimport time # sample function that returns square# of the value passeddef print_square(x):    return (x**2) # records the time at this instant of the# programstart = time.perf_counter() # calls the functionprint_square(3) # records the time at this instant of the# programend = time.perf_counter() # printing the execution time by subtracting# the time before the function from# the time after the functionprint(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.time_ns() 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 moduleimport time # sample function that returns square# of the value passeddef print_square(x):    return (x**2) # records the time in nanoseceonds at# this instant of the programstart = time.time_ns() # calls the functionprint_square(3) # records the time in nanoseceonds at this# instant of the programend = time.time_ns() # printing the execution time by subtracting# the time before the function from# the time after the functionprint(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.
To measure the elapsed time or execution time, we can use time.process_time() function. This follows the same syntax as the time.process_time()) 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.
Python3
# importing the moduleimport time # sample function that returns square# of the value passeddef print_square(x):    return (x**76567) # records the time in nanoseceonds at# this instant of the programstart = time.process_time() # calls the functionprint_square(125) # records the time in nanoseceonds at this# instant of the programend = time.process_time() # printing the execution time by subtracting# the time before the function from# the time after the functionprint(end-start)
0.015625
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 is 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 modulefrom datetime import datetime # sample function that returns square# of the value passeddef print_square(x):    return (x**2) # records the time at this instant of# the program in HH:MM:SS formatstart = datetime.now() # calls the functionprint_square(3) # records the time at this instant of the# program in HH:MM:SS formatend = datetime.now() # printing the execution time by subtracting# the time before the function from# the time after the functionprint(end-start)
Output:
0:00:00
surajkumarguptaintern
Picked
Python time-module
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.