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

def BinarySearch(arr, val):
    first = 0
    last = len(arr)-1
    index = -1
    while (first <= last) and (index == -1):
        mid = (first+last)//2
        if arr[mid] == val:
            index = mid
        else:
            if val<arr[mid]:
                last = mid -1
            else:
                first = mid +1
    return 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 module

def BinarySearch(arr, val):
  first = 0
  last = len(arr)-1
  index = -1
  while (first <= last) and (index == -1):
      mid = (first+last)//2
      if arr[mid] == val:
          index = mid
      else:
          if val<arr[mid]:
              last = mid -1
          else:
              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 runtime

end= time.time() #store the ending time
time= "{:.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.

Do drop your views in the comment section 😊.

21