Path: blob/master/12-Advanced Python Modules/06-Timing your code - timeit.ipynb
666 views
Timing your code
Sometimes it's important to know how long your code is taking to run, or at least know if a particular line of code is slowing down your entire project. Python has a built-in timing module to do this.
Example Function or Script
Here we have two functions that do the same thing, but in different ways. How can we tell which one is more efficient? Let's time it!
Timing Start and Stop
We can try using the time module to simply calculate the elapsed time for the code. Keep in mind, due to the time module's precision, the code needs to take at least 0.1 seconds to complete.
Timeit Module
What if we have two blocks of code that are quite fast, the difference from the time.time() method may not be enough to tell which is fater. In this case, we can use the timeit module.
The timeit module takes in two strings, a statement (stmt) and a setup. It then runs the setup code and runs the stmt code some n number of times and reports back average length of time it took.
The setup (anything that needs to be defined beforehand, such as def functions.)
Now let try running func_two 10,000 times and compare the length of time it took.
It looks like func_two is more efficient. You can specify more number of runs if you want to clarify the different for fast performing functions.
Timing you code with Jupyter "magic" method
NOTE: This method is ONLY available in Jupyter and the magic command needs to be at the top of the cell with nothing above it (not even commented code)
Great! Check out the documentation for more information: https://docs.python.org/3/library/timeit.html