Open In App

How to measure elapsed time in Python?

Last Updated : 31 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




# importing the module
import timeit
 
# define the code statement to test and
# calculate the execution time
exec_time = timeit.timeit("print('Hello World!')")
 
# printing the execution time in seconds
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




# importing the module
import timeit
 
 
# code segment to measure
code_segment = '''\
import random
def execute(n):
    return n**n
execute(random.randint(20, 50))
'''
 
# execute code segment and find the execution time
exec_time = timeit.timeit(code_segment, number=10**6)
 
# printing the execution time in secs.
# nearest to 3-decimal places
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




# importing the module
import timeit
 
 
# function to test the execution time
def print_square(x):
    return x ** 2
 
 
t_records = timeit.repeat(lambda: print_square(3), number=10, repeat=5)
 
# printing the execution time
for index, exec_time in enumerate(t_records, 1):
    # printing execution time of code in microseconds
    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




# importing the module
import timeit
 
 
# define function
def print_square(x):
    return x ** 2
 
 
# record start time
t_0 = timeit.default_timer()
# call function
res = print_square(11111111)
# record end time
t_1 = timeit.default_timer()
 
# calculate elapsed time and print
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




# importing the module
import time
 
 
# function to test elapsed time for
def print_square(x):
    return x ** 2
 
 
# records start time
start = time.perf_counter()
 
# calls the function
print_square(3)
 
# record end time
end = time.perf_counter()
 
# find elapsed time in seconds
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




# importing the module
import time
 
# sample function for testing
def print_square(x):
    return (x**2)
 
# record start time
start = time.time_ns()
 
# calls the function
print_square(3)
 
# record end time
end = time.time_ns()
 
# printing elapsed time in nanoseconds
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




# importing the module
import time
 
 
# sample function for testing
def print_square(x):
    return x ** 76567
 
 
# record start time
start = time.process_time()
 
# calls the function
print_square(125)
 
# record end time
end = time.process_time()
 
# print elapsed time in seconds
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




# importing the module
from datetime import datetime
 
 
# sample function for testing
def print_square(x):
    return x ** 2
 
 
# record start time (in datetime format)
start = datetime.now()
 
# calls the function
print_square(3)
 
# record rnd time (in datetime format)
end = datetime.now()
 
# print elapsed time in microseconds
print("Elapsed", (end - start).total_seconds() * 10**6, "µs")


Output:

Elapsed 12.0 µs


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads