Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

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. The timeit module contains a number of functions. The one we'll focus on is named timeit. This function creates a Timer object for some statement. It can also include some setup code that prepares the environment. It then calls the timeit() method of Timer to execute the setup just once and the target statement repeatedly. The return value is the time required to run the statement.

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

The following is a simple interaction with timeit:

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