In this tutorial, we will know how to find the execution time in a Python program. So, first of all, let’s understand what is the execution time in python.
What is an Execution Time
When the code executes on the server then whatever time the server takes to execute the code is called execution time of the program.
Problem to Finding the Execution Time in Python
Suppose, If you have two functions written in your application to fulfill the same problem.
def function1(fname): print(fname + " Hunger") function1("Techy") // output: Techy Hunger // def function2(fname, lname): print(fname + " " + lname) function2("Techy", "Hunger") // output: Techy Hunger
So when your code executes then how you will measure the efficiency of both functions because the response comes in milliseconds and the results are the same.
Why You Should Take Care of Program Execution Time
At the time of writing any program or function in python or any other languages, you should always take care of this.
Because if your code executes fast then your other functions will also be executed fast and easily and that’s why you will have less load on the server.
and of course, a fast website is always rank fast on google search engine.
Find Execution Time in Python Using Time Module
Python has a very useful built-in function called time. Let’s see how you can use this module to measure the execution time of a python program.
Now, modify our both functions written in the above code block:
from time import time def function1(num1, num2): return num1 + num2 def function2(num1, num2): if( num1 > 100 and num2 < 100 ): pass return num1 + num2 if __name__ == '__main__': init = time() function1(5, 7) print("Function 1 execution time", time() - init) init = time() function2(5, 7) print("Function 2 execution time", time() - init)
Now, when you run the above code you will find the different execution times for both the function.
In the above code, you can see a line ‘if __name__ == ‘__main__’:’.
What is this and what is the use of ‘if __name__ == ‘__main__’:’ here.
Actually, whenever the Python interpreter starts reading a source file, it does two things:
- it sets a few special variables like __name__,
- and then, it executes all of the code found in the code file.
You can find a detailed explanation here – What does if __name__ == “__main__”: do?
As you can see, how easy it is to find execution time in a python program. So start writing some function or program and try to find the execution time.