While the first rule of optimization might be "don't do this," the second rule almost certainly says, "Don't optimize the irrelevant." To this end, if your program is running slowly, you can start by profiling your code. More often than not, you find that a program is wasting its time on multiple hotspots, such as internal data loops. Once these locations are determined, all the necessary techniques can be used to speed up the program.
Many programmers start using Python as a language for writing simple scripts. When writing scripts, it is easy to fall into the practice of simply writing code with very little structure.
Code # 1: With this code in mind.
A little known fact is that code defined in the global scope is slower than code defined in a function. The difference in speed is related to the implementation of local and global variables (operations involving local operators are faster). So, just put script statements in a function to make the program run faster.
Code # 2:
The difference in speed is strong depends on the processing being performed, but 15-30% speedups are not uncommon.
Each use of the dot (.) operator to access attributes is expensive ... In disguise, this calls special methods like
__getattribute __ () and
__getattr __ () , which often result in
__getattr __ () in the dictionary. p>
It is often possible to avoid looking for attributes by using an import form and also choosing to use related methods as shown in the code snippet below —
Code # 3: strong>
This program runs in about 29 seconds when running on the machine.
The only difference between the two versions of the code is the exclusion of access to attributes. Instead of using
math.sqrt () , the code uses
sqrt () . The
result.append () method is additionally placed in the local variable re
sult_append and reused in the inner loop.
However, it should be emphasized that these changes only make sense in code that is executed frequently, such as for loops. Thus, this optimization really only makes sense in carefully selected places.
As noted earlier, local variables are faster than global variables. For commonly used names, accelerations can be obtained by making these names as local as possible.
Code # 5: Modified version of
compute_roots() p >
In this release, sqrt has been removed from the math module and placed in a local variable. This code will run for about 25 seconds (an improvement over the previous version, which took 29 seconds). This additional speedup is due to the fact that the local sqrt search is slightly faster than the global sqrt search.
Locality arguments also apply when working in classes. In general, finding a value such as
self.name will be significantly slower than accessing a local variable. Inner loops may need to hoist public attributes into a local variable, as shown in the code below.
Code # 6: