How to calculate the run time of a codes

How to calculate the run time of a codes

you probably heard about something called Big O notation, one of the major tasks in all programming in which part of it is calculating the time complexity.

what is time complexity??

time complexity is the process of calculating the time taken for specific codes to run as the argument or data becomes larger. this tells us the worse we might experience while making use of our codes. it also tells us how good our codes are, as you know there is no specific way of solving the problem with codes but calculating the time complexity tells us the best way of doing it.

How do I calculate the run time of my codes?? to calculate the runtime of your codes is nothing hard, all you have to do is to follow the following process.

  1. Import the time library and declare a variable name to hold the start time.
  2. write all the codes you want to calculate its run time
  3. declare a variable to hold the end time
  4. subtract the starting time from the end time.
  5. print the difference between the two times. Now let's take a look at some examples.

Example

the following shows the codes to display the list of all even number between 1 and 2500 exclusive. Codes

from time Import time
startTime=time()#hold the begining time
listEven=[]
for i in range(1,2500):
    listEven.append(2*i)
print(listEven)
endTime=time()#hold the time the codes end
time_difference=endTime-startTime
print(time_difference)

Result

0.015599966049194336

as you can see here we have a list and the run time printed. Although, only the run time is stated above as that is our topic of interest we are not interested in the list itself. Now let's see another way we could have gotten the same list.

method2

codes


from time import time
startTime=time()
listEven=[i*2 for i in range(1,2500)]
print(listEven)
endTime=time()
print(endTime-startTime)

Result>>

0.004999876022338867

can you see the time taken to run the codes?? both the first and second methods solved the same problem? however, the second method is three times faster than the first method. Hence, the second method will be the better way to solve the problem.

A question that might be bothering you is "why do I need to choose the second method??" well looking at the time taken for each to run we might say there is no significant difference. However, when you are dealing with big data this will show the difference. for example, you can try to change the problem to all even numbers between 1 and 500 000 and see how long it takes.

I hope you find this article helpful, consider to share to a friend who might also like to read this. you are free to chat me up on WhatsApp, Facebook or mail me if you have any questions. enjoy coding!