Performance – the timeit module

We'll make use of the timeit module to compare the actual performance of different object-oriented designs and Python constructs. We'll focus on the timeit() function in this module. This function creates a Timer object that's used to measure the execution of a given block of code. We can also provide some preparatory code that creates an environment. The return value from this function is the time required to run the given block of code.

The default count is 100,000. This provides a meaningful time that averages out other OS-level activity on the computer doing the measurement. For complex or long-running statements, a lower count may be prudent.

Here's a simple interaction with timeit:

>>> timeit.timeit("obj.method()", 
... """
... class SomeClass:
... def method(self):
... pass
... obj= SomeClass()
... """)
0.1980541350058047

The code to be measured is obj.method(). It is provided to timeit() as a string. The setup code block is the class definition and object construction. This code block, too, is provided as a string. 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.

This example showed that 100,000 method calls that do nothing costs 0.198 seconds.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset