How to measure elapsed time in Python?
Last Updated :
31 Aug, 2022
In Python, we can measure the elapsed time on executing a code segment or a Python script using some built-in Python modules. Here we will cover the usage of time, timeit and datetime module.
Using Python timeit Module to measure 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 while calculating the time of execution.
Example 1: Analyze how to use the timeit module
In this example, we will 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 timeit module, and then we use the timeit() function from the module to find the execution time of the function.
Python3
import timeit
exec_time = timeit.timeit( "print('Hello World!')" )
print (exec_time, "secs." )
|
Output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
...
1.632629341998836 secs.
Explanation: The above code segment, will print “Hello World” 1000000 times (since default value of number parameter is 1000000). At the end, the code will print the execution time of the given code segment, measured in seconds.
Example 2: Using timeit.timeit() with predefined parameters
In this example, we’ll write a Python code segment having a function, and it’s call as a string and pass it to timeit.timeit() function. We’ll use a predefined number of iterations to count the execution time.
Python3
import timeit
code_segment =
exec_time = timeit.timeit(code_segment, number = 10 * * 6 )
print (f "{exec_time:.03f} secs." )
|
Output:
1.118 secs.
Explanations: In this example, we have defined a Python function and call to the function, everything written as a string representation. We test the running time of the code for 10**6 times and print out the time taken to execute the given function in seconds.
Example 3: How to measure elapsed time using timeit.repeat
We 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. This helps in getting an average elapsed time value from multiple execution of the same code segment.
Python3
import timeit
def print_square(x):
return x * * 2
t_records = timeit.repeat( lambda : print_square( 3 ), number = 10 , repeat = 5 )
for index, exec_time in enumerate (t_records, 1 ):
m_secs = round (exec_time * 10 * * 6 , 2 )
print (f "Case {index}: Time Taken: {m_secs}µs" )
|
Output:
Case 1: Time Taken: 4.41µs
Case 2: Time Taken: 3.15µs
Case 3: Time Taken: 3.07µs
Case 4: Time Taken: 3.04µs
Case 5: Time Taken: 3.08µs
Example 4: How to measure elapsed time using timeit.default_timer()
timeit.default_timer() uses the timeit.perf_counter() to record the timestamp of an instance in nanoseconds, and we can subtract end time from start time to get the execution time duration in nanoseconds.
Python3
import timeit
def print_square(x):
return x * * 2
t_0 = timeit.default_timer()
res = print_square( 11111111 )
t_1 = timeit.default_timer()
elapsed_time = round ((t_1 - t_0) * 10 * * 6 , 3 )
print (f "Elapsed time: {elapsed_time} µs" )
|
Output:
Elapsed time: 1.266 µs
Using Python time Module to measure elapsed time in Python
In Python time module, there are different methods to record and find the execution time of a given code segment, we covered the usage of the following methods: time.perf_counter(), time.time_ns(), time.process_time(), time.time()
Example 1: How to measure elapsed time using time.perf_counter()
time.perf_counter() method records the time in seconds time unit. Since our sample function is very simple, so, we need to convert it to micro seconds to get time difference value in readable format.
Python3
import time
def print_square(x):
return x * * 2
start = time.perf_counter()
print_square( 3 )
end = time.perf_counter()
ms = (end - start) * 10 * * 6
print (f "Elapsed {ms:.03f} micro secs." )
|
Output:
Elapsed 1.014 micro secs.
Example 2: How to measure elapsed time using time.time_ns()
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() 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
import time
def print_square(x):
return (x * * 2 )
start = time.time_ns()
print_square( 3 )
end = time.time_ns()
print ( "Time taken" , end - start, "ns" )
|
Output:
Time taken 2671 ns
Example 3: How to measure elapsed time using time.process_time()
time.process_time() function returns the sum of the system and the user CPU time. This follows the same syntax as the time.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
import time
def print_square(x):
return x * * 76567
start = time.process_time()
print_square( 125 )
end = time.process_time()
print ( "Elapsed time using process_time()" , (end - start) * 10 * * 3 , "ms." )
|
Elapsed time using process_time() 12.583209999999998 ms.
Using Python datetime Module to measure elapsed time in Python
we can also use Python datetime module, we can also record time and find the execution time of a block of code. The process is same as using time.time(), measuring start and end time and then calculating the difference.
Example: How to measure elapsed time using datetime.datetime.now()
Python3
from datetime import datetime
def print_square(x):
return x * * 2
start = datetime.now()
print_square( 3 )
end = datetime.now()
print ( "Elapsed" , (end - start).total_seconds() * 10 * * 6 , "µs" )
|
Output:
Elapsed 12.0 µs
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...