INTRODUCTION
MEASURING THE EXECUTION TIME OF A PYTHON PROGRAM:
The python programs understanding is very important to utilize the resource efficiently. By measuring the execution time of the program, the programmer can understand how much time does the program takes to execute. There are several ways to measure the time taken by the program. Let us look into the different ways to measure the time of execution.
1.) Using the time module.
The time module is one of the best ways to find the execution time of the program. This module tracks the time before and after the execution of the program then it finally calculates the execution time by subtracting the before and after time. let us look into a simple code using the time module.
import time s_time = time.time() code = sum(range(10000)) e_time = time.time() exe_time = e_time - s_time print("execution time: {exe_time} seconds")
In the above program we calculate the execution time by importing the time module. Here the time.time() records the current time in seconds . Here the s time indicates the start time and the e time indicates the end time. Then by subtracting the start time from end time we can find out the execution time and print it. exe time indicates the execution time in the above program.
let us look into one more type
2.) Using the timeit() module.
The timeit module is used to measure the execution time of small programs more accurately than the time module . It minimizes the system impact and other factors that ruins the results by running the code multiple times and averaging the results.
let us look into a small program.
import timeit code = """ result = sum(range(100000))""" exe_time = timeit.timeit(code,number=1000) print("execution time for 1000 runs: {exe_time}seconds")
Here the timeit.timeit() runs the code 1000 times and returns the total time taken. This method is useful for obtaining a more reliable measure of execution time for small functions or code blocks.