What is the timeit python module
The timeit python module measures the execution time of python functions. Timeit is more precise than finding the difference of the start time and end time of a function. In addition to being more precise, timeit executes the snippet multiple times providing a more accurate depiction of the average execution time. In order to get started with the timeit python module, you should install ipython using pip.
Developing functions to test
Prior to using timeit, we must develop a function to test. Below you can find simple script with two functions, both of which return the age associated with the name of the person found in the list. One uses a for loop to find the index of the name and uses the index to find the age. The other zips the two list together, finds the name, and returns the associated age.
from timeit import timeit names = ['Adam', 'Brandon', 'Carlie', 'David', 'Emily', 'Frank', 'Greg', 'Heather', 'Isaac', 'Jacob'] ages = [43, 35, 24, 65, 42, 30, 28, 19, 21, 39] def find_age(search_name): for i, person in enumerate(names): if search_name == person: return ages[i] def find_age_zip(search_name): for name, age in zip(names, ages): if name == search_name: return age
Using ipython to time our functions
Now that we have python functions to test, we can place them in a new python file called test.py. In our terminal window, we can start ipython notebook by simply typing “ipython.” This will start an ipython shell. In our shell we can type the following:
%run test.py %timeit find_age('Adam') %timeit find_age_zip('Adam')
The timeit python module is a great tool to test the execution time of functions and other code snippets. With the help of ipython, the timeit module is very intuitive.
If you have further questions regarding timeit or execution time, don’t hesitate to contact us.