How to calculate time of execution in python
Calculating the time of execution, also known as timing a code, can be useful to determine how long a certain task takes to complete. In Python, there are several ways to do this, and in this blog post, we’ll go over some of the most common methods.
1. time module:
The time module provides a function called time() that returns the current time in seconds since the epoch (the point in time at which time starts). To calculate the time of execution of a specific piece of code, you can get the current time before and after the code, and then subtract the two times to get the duration. Here’s an example:
import time
start_time = time.time()
# Your code here
end_time = time.time()
duration = end_time - start_time
print("Time of execution:", duration, "seconds")
2. perf_counter function:
Another option to measure the time of execution is to use the perf_counter function from the time module. This function is similar to time(), but it provides higher precision and is recommended for timing purposes. Here’s an example:
import time
start_time = time.perf_counter()
# Your code here
end_time = time.perf_counter()
duration = end_time - start_time
print("Time of execution:", duration, "seconds")
3. timeit module:
The timeit module provides a convenient way to time the execution of small bits of Python code. The timeit function takes a string that contains the code to be executed and the number of loops, and returns the time it takes to execute the code. Here’s an example:
import timeit
code = """
# Your code here
"""
duration = timeit.timeit(code, number=1000)
print("Time of execution:", duration, "seconds")
In this example, the timeit function will execute the code in the code string 1000 times and return the total time it took.
These are some of the most common methods for calculating the time of execution in Python. Depending on your needs and the specifics of your code, you can choose the one that works best for you.