Resolved: How do Timer() and timeit() work?
Good evening. What's the difference between Timer() and timeit()? It's not clear how they work. Why "timeit.Timer("fib(36)", "from greetings import fib")" has 2 strings inside and why "t1.timeit(5)" has a 5 inside? What do they mean? Thank you
Thank you for your question!
First, a couple of things to note in Giles' example. There is the module timeit which Giles imports on line 160. Then, there is the class Timer which he uses on lines 163 and 166 - it has a method timeit() which he uses on lines 164 and 167. Lastly, there exists a separate method timeit which Giles doesn't use in this example. It directly creates an instance of the
Timer class. Let me demonstrate this with two examples that perform the same task.
1. Using the
Timer class and its
As you can find in the documentation,
Timer has a couple of parameters -
timer (which is a bit more technical, so I won't mention it below), and
stmt, you specify the piece of code whose execution time you want to get - in our case, that is fib(36), so we write it as a string. Now, we move on to the
setup parameter. As the
timeit module works within its own namespace, it won't recognize the function
fib(n). Therefore, we need to tell
timeit that we want it to look in our namespace. This is done using the code from the screenshot above. As it turns out, there is another way to do it by making use of the
In contrast, Giles'
fib function is defined in the
greetings module, so he imports it from there. The
globals parameter would have not worked for him.
So far, in line 11, we've created an instance of the
Timer class. In order to get the time for execution, however, we need to call
timeit() method and specify the number of times we want our code to be executed through the
number parameter. By default this number is quite big - 1,000,000. However, we can change it by setting the
number parameter to 5, for example. Running this piece of code, we will obtain the time for execution.
2. Another way of arriving at the same result is by directly using the
timeit() method from the
timeit module. It is done as follows:
Note that we can directly specify the
number parameter. Note also that you can again use the
setup parameter instead of
It becomes very intuitive once you try it out a couple of times. I hope this helps! :)