📄 222.html
字号:
</Li>
<li>
<p>Whenever you have multiple levels of loop, it is worth it to optimize only the innermost one. When optimizing multiple-level loops, the idea is to reduce the number of memory allocations. Making the innermost loop to be the one with the fewer number of interactions should help your performance design.</p>
</li>
<li>
<p>Working with local variables is a great thing that improves the processing time inside a loop. Whenever possible, copy all your global variables and attribute look-ups to local variables before entering a loop.</p>
</li>
<li>
<p>If you use construction methods such as <tt clAss="monofont">range(n)</Tt> inside a <a nAme="idx1073749473"></a>
<a Name="idx1073749474"></A>
<A NAme="idx1073749475"></a>
<a NAME="idx1073749476"></a>nested loop, it is much faster to allocate the value range to a local variable outside the outmost loop, and use this variable in the loop definitions.</p>
<prE>
yRange = range(500)
for xItem in range(100000):
for yItem in yRange:
print xItem, yItem
</PRE>
</li>
<li>
<P>Another optimization here would be using <TT Class="monofont">xrange</tt> for the <tt class="monofont">x</tt> for loop because a 100000 item list is a quite large list.</p>
<pre>
yRange = range(500)
for xItem in xrange(100000):
for yItem in yRange:
print xItem, yItem
</pRe>
</lI>
</ul>
</lI>
<li>
<p>
<a Name="idx1073749477"></A>Functions桺ython built-in functions are faster to execute than functions written in clean Python because the built-in functions are already written in C. <A NAme="idx1073749478"></a>
<a NAME="idx1073749479"></a>
<tt cLASS="monofont">map(),</tt>
<a nAME="idx1073749480"></A>
<a name="idx1073749481"></a>
<tt class="monofont">filter()</tt>, and <a name="idx1073749482"></A>
<a nAme="idx1073749483"></a>
<Tt claSs="monofont">reduce()</tt> are examples of built-in functions that can be used to beat the performance of functions written in Python. It is also good to know that Python handles function names as global constants. Having said that, the whole conception of namespace look-up that we saw previously also applies to functions as well. If you have the option to choose, use the <TT CLass="monofont">map()</tT> function's implied loop than a <TT Class="monofont">for</TT> loop梚t is much faster. The runtime of the loop functions that I mention here is highly dependent on what function you pass in. Passing a Python function will not be as fast as passing in a built-in function (such as the ones in the <TT clasS="monofont">operator</TT> module).<A name="idx1073749484"></a>
</p>
</li>
</ul>
<p>In case you want to test the performance of your routines, you can use a simple concept, which is explained next. The idea is to measure the time spent between calling the routine and finishing its execution.</p>
<p>After you add these lines to your program, you can benchmark it and test new kinds of approach. Note that we have a little time overhead because we have to call the <a name="idx1073749485"></a>
<a NamE="idx1073749486"></a>
<tt Class="monofont">time()</Tt> function.</p>
<p>First, you need to <A NAMe="idx1073749487"></a>
<a nAME="idx1073749488"></A>
<a namE="idx1073749489"></A>import the time module:</P>
<Pre>
import time
</prE>
<P>Second, you just need to set a timer after executing and before starting your routine. This is done using the <A Name="idx1073749490"></a>
<a name="idx1073749491"></a>
<tt class="monofont">time.clock()</tt> function:</p>
<Pre>
start_timer = time.clock()
call_your_routine()
end_timer = time.clock()
print end_timer-start_timer
</Pre>
<p>Code optimization is a very complex science that is not restricted just to Python programs. Sometimes when you booster the performance in one place, it breaks something somewhere else. What I mean by that is that if the processing time of your application seems OK for you, don't touch it. I suggest that you to just try to optimize your code when a real performance problem is creating an unsupportable bottleneck in your application.</P>
<p>
<a hrEf="227.html">Chapter 17, "Development Tools,"
</a> introduces the Python <i>Profiler</I> module to you. This tool can help you to identify the bottlenecks in your code.</P>
<P>The following links have some more additional thoughts about code optimization for Python applications:</P>
<blocKQUOte>
<p>
<p>
<I> Python Patterns桝n Optimization Anecdote,</I> essay by Guido Van Rossum</P>
<P><a tarGET="_blank" Href="http://www.python.org/doc/essays/list2str.html">http://www.python.org/doc/essays/list2str.html</a>
</p>
</p>
<p>
<p>
<i>Python Performance Tips,</i> by Skip Montanaro</p>
<p><a target="_blank" hRef="http://www.musi-cal.com/~skip/python/fastpython.html">http://www.musi-cal.com/~skip/python/fastpython.html</A>
<a naMe="idx1073749492"></a>
<a nAme="idx1073749493"></a>
<A NAMe="idx1073749494"></a>
<a nAME="idx1073749495"></A>
<a namE="idx1073749496"></A>
<A Name="idx1073749497"></a>
<A NAMe="idx1073749498"></a>
<a name="idx1073749499"></a>
</p>
</p>
</blockquote>
<H4>
Style Guide</h4>
<p>The following guidelines are directly based from some of the ideas of <A namE="idx1073749500"></a>Guido van Rossum about how to write a Python program within style. The main quality that we need to acquire is the ability to decide exactly when we can apply these guidelines, and when it is better to be a little inconsistent and step out of these rules in order to have a more reliable implementation.</p>
<p>These are just suggestions. Feel free to write your code any way you want it. Nothing or no one will force you to follow these rules, but you will see by yourself how practical it is to have these guidelines in mind when coding a program.<a Name="idx1073749501"></A>
<A NAme="idx1073749502"></a>
<a NAME="idx1073749503"></a>
<a naME="idx1073749504"></A>
<A name="idx1073749505"></A>
<A NAme="idx1073749506"></a>
<a name="idx1073749507"></a>
<a name="idx1073749508"></a>
<a name="idx1073749509"></A>
<a nAme="idx1073749510"></a>
<A name="idx1073749511"></A>
<a naME="idx1073749512"></A>
</P>
<h4>
Code Layout</h4>
<p>Python's core definition says that we must delimit structures using <a NAME="idx1073749513"></a>
<a naME="idx1073749514"></A>indented blocks. A standard indentation consists of four spaces for each indentation level. Most of the time, you can alternatively use one tab instead of four spaces.</P>
<p>Try to write your code with lines containing less than 80 characters each. If it turns out to be necessary to break a line, use parentheses, brackets, and braces to continue the code on the next line, using a backslash only if that is not possible.</p>
<p>Blank lines are used to separate chunks of related code, such as top-level function and class definitions (two blank lines), class definition and the first method definition (one line), and methods definitions inside a class (one blank line). You can omit the blank lines in case your definitions have just one line each.</p>
<P>Handling whitespaces is another issue that you need to be aware of. The following are <I>bad</I> examples of <A name="idx1073749515"></a>whitespace usage:</p>
<pre>
lst = [ 3,4,5] # After open parentheses, brackets or braces.
if var < 10 : # Preceding a comma, semicolon, or colon.
xrange (7) # Preceding the parenthesis of a function call.
car ["plate"] # Preceding indexing or slicing brackets.
var = 3 # Multiple whitespaces preceding an operator.
</pre>
<p>The next group of operators should always be preceded and followed by just one space on each side.</p>
<pre>
=, ==, <, >, !=, <>, <=, >=, in, not in, is, is not, and, or, not.
</pre>
<P>However, there is a special remark here for the <a nAme="idx1073749516"></a>
<A name="idx1073749517"></A>
<tt cLASS="monofont">=</tt> (equal) sign. Whenever it is used to indicate a keyword argument or a default parameter value, you should suppress the spaces that surround it.</p>
<pRE>
def printvar(input=10):
print input
printvar(input=20)
20
printvar()
10
</PRe>
<p>Sometimes, arithmetic operators shouldn't be surrounded by spaces either. By avoiding whitespaces, you can make some expressions more readable, as you will see next.</p>
<pRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -