Timing how long it takes for a code snippet to run is a good way to measure the performance of your code. Though this doesn't really give the accurate measurement of the performance of your code snippet, but it gives you an idea of the increase or decrease in the performance of your code snippet.
In this short post, I'll be giving you tips on how to use the timeit python module in measuring your python code snippet.
timeit is a built-in Python module that provides a simple way to time small bits of python code. This Module can be used from the Command-Line Interface(CLI) or can be imported to your code and called.
Using timeit within your code
import timeit
def myFunction():
for i in range(1000):
print (i*i)
print(timeit.timeit(myFunction, number=1))
In the code, we are looping through a range of 100 and printing the multiple of each step. Then we printed the time it took the code to run once(number=1) using the timeit method of the timeit module. The function takes to arguments:
- The name of the function to time
- The number of times we want to run the run the function. When the number of time is set, it returns the time it took to run the function in the given number of times.
If we want to know how long it will take for the function to run 10 times, then we have to specify that in the number argument:
import timeit
def myFunction():
for i in range(1000):
print (i*i)
print(timeit.timeit(myFunction, number=10))
It's important to note that the output of running this code would be the number of times it took to run the myFunction function in seconds. If you would like to get home times it took to run once, you can set the value number argument to 1 or divide by the value of number set.
This is just the basic use case of the timeit module. There are other methods available on the timeit modules and can be found in the python module documentation
Hope this was helpful, feel free to contribute and let me know if I missed something.
Top comments (0)