Performance Considerations

The execution of a Python program is mostly a sequence of function calls involving the special methods described in the earlier section “Special Methods.” If you find that a program runs slowly, you should first check to see if you’re using the most efficient algorithm. After that, considerable performance gains can be made simply by understanding Python’s object model and trying to eliminate the number of special method calls that occur during execution.

For example, you might try to minimize the number of name lookups on modules and classes. For example, consider the following code:

import math
d= 0.0
for i in xrange(1000000):
     d = d + math.sqrt(i)

In this case, each iteration of the loop involves two name lookups. ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.