Python – Find execution time of a function
To compute the execution time of a function in Python, we can use timeit library.
timeit.timeit() computes the execution time of a given statement for specified number of times.
For example, the following expression computes how much time the
sum(range(100)) statement took to execute for
Since sum() is a builtin function, we have not passed any argument for the setup parameter to timeit() function. But, if we have a custom function, or code, we have to pass all of the code we need to test as a string argument to the setup parameter.
For example, in the following program, we have taken a function
sum_x() defined and taken in a string variable setup. We will test how much time it takes to execute for
Note: If we do not specify the number of times the statement has to execute, it does for a million times.
import timeit code_setup = ''' def sum_x(x): sum = 0 for i in range(x): sum += i ''' seconds = timeit.timeit('sum_x(5000)', setup = code_setup, number=1000) print('Time :', seconds)
Time : 0.13776170799974352
So, it took roughly 0.13 seconds to execute the statement
sum_x(5000) for a thousand times.
If you would like to find the time taken for one time execution of given statement, divide the returned seconds by the number argument. That way, we can average the execution time.
This is how you test the performance or time taken by a piece of code, or a function, using timeit.timeit() function.
In this tutorial of Python Examples, we learned how to compute the execution time of a function, for specified number of times, using requests module.