Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!A given problem may be solved by more than one alternative algorithms. Hence, we need to optimize the performance of the solution. Python's timeit module is a useful tool to measure the performance of a Python application.
The timit() function in this module measures execution time of your Python code.
Syntax
Parameters
-
stmt − code snippet for measurement of performance.
-
setup − setup details arguments to be passed or variables.
-
timer − uses default timer, so, it may be skipped.
-
number − the code will be executed this number of times. The default is 1000000.
Example
The following statement uses list comprehension to return a list of multiple of 2 for each number in the range upto 100.
To measure the execution time of the above statement, we use the timeit() function as follows −
Compare the execution time with the process of appending the numbers using a for loop.
The result shows that list comprehension is more efficient.
The statement string can contain a Python function to which one or more arguments My be passed as setup code.
We shall find and compare the execution time of a factorial function using a loop with that of its recursive version.
The normal function using for loop is −
Definition of recursive factorial.
Test these functions to calculate factorial of 10.
Now we shall find their respective execution time with timeit() function.
Output
Performance of factorial function with loop 0.00330029999895487 Performance of factorial function with Recursion 0.006506800003990065
The recursive function is slower than the function with loop.
In this way, we can perform performance measurement of Python code.
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.