Tip
Downloading the example code
You can download the example code files for all Packt Publishing books you have purchased from your account at http://www.packtpub.com. If you have purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
The statement obj.method()
is provided to timeit()
as a string. The setup is the class definition and is provided as a string as well. It's important to note that everything required by the statement must be in the setup. This includes all imports as well as all variable definitions and object creation. Everything.
It can take a few tries to get the setup complete. When using interactive Python, we often lose track of global variables and imports that have scrolled off the top of the terminal window. This example showed that 100,000 method calls that do nothing take 0.198 seconds.
The following is another example of using timeit
:
>>> timeit.timeit( "f()",""" ... def f(): ... pass ... """ ) 0.13721893899491988
This shows us that a do-nothing function call is slightly less expensive than a do-nothing method invocation. The overhead in this case is almost 44 percent.
In some cases, OS overheads may be a measurable component of the performance. These tend to vary based on factors that are hard to control. We can use the repeat()
function instead of the timeit()
function in this module. It will collect multiple samples of the basic timing to allow further analysis of OS effects on performance.
For our purposes, the timeit()
function will provide all the feedback we need to measure the various object-oriented design considerations objectively.