This website collects cookies to deliver better user experience
Find the Script Execution Time in Python
Find the Script Execution Time in Python
Being a Programmer our main aim will be to optimize the program and make sure it take less time to execute it.
Using the Time module in Python we can find the execution time of the program.
Lets start it by writing a simple python script
defBinarySearch(arr, val): first =0 last =len(arr)-1 index =-1while(first <= last)and(index ==-1): mid =(first+last)//2if arr[mid]== val: index = mid
else:if val<arr[mid]: last = mid -1else: first = mid +1return index
array =[10,7,8,1,2,4,3]result = BinarySearch(array,4)
So now lets import the time module and
Initiate a variable to store the time at the beginning of the execution ,
Initiate another variable at the end to store the time after the execution ,
Then find the difference between the start and the end time to get the time required for the execution.
import time #import the moduledefBinarySearch(arr, val): first =0 last =len(arr)-1 index =-1while(first <= last)and(index ==-1): mid =(first+last)//2if arr[mid]== val: index = mid
else:if val<arr[mid]: last = mid -1else: first = mid +1 reurn index
start = time.time()#store the starting time a=[1,2,3,4,5,6,7,8,9,10]result = BinarySearch(a,5)print(f'Number found at {result}')time.sleep(1)# sleeping for 1 sec to get 10 sec runtimeend= time.time()#store the ending timetime="{:.3f}".format(end - start)#time required for the execution print(f"time required : {time} sec")
so the output will be like ...
@nilavya~/Desktop
> python script.py
Number found at 4
time required : 1.001 sec
@nilavya~/Desktop
>
So in this way we can get the time required for the execution.
Calculating the time of execution of any program is very useful for optimizing your python script to perform better.
The technique come in handy when you have to optimize some complex algorithm in Python.