Using time profiling we can identify which parts of the code are taking the most time and we can optimize that part and improve the overall efficiency of our program. In this article, we will see different ways to perform time profiling in Python.
Methods for Time Profiling
Time module
The simplest way to measure execution time is by using the time
module. time
is an in-built Python module.
First, import the time module and record the start time before the function execution time and the end time after the function execution.
Now, calculate the Execution Time by subtracting the start time from the end.
Example:
import time
def function_to_profile():
time.sleep(2)
start_time = time.time()
function_to_profile()
end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time} seconds")
Using the Timeit module
If we need to measure the performance even more accurately i.e., especially for the small snippets, use the timeit
module.
import the timeit
module and then define the function you want to do the time profiling.
Now, use the timeit.timeit
to measure the execution time. The number
parameter specifies how many times you want to measure the performance of this function. See the following example for more information on this.
import timeit
def do_range():
return sum([i for i in range(1000)])
execution_time = timeit.timeit("do_range()", globals=globals(), number=1000)
print(f"Execution time: {execution_time} seconds")