236.html
来自「Python Ebook Python&XML」· HTML 代码 · 共 411 行 · 第 1/2 页
HTML
411 行
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Robots" content="INDEX,NOFOLLOW">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<TITLE>Safari | Python Developer's Handbook -> Profiling Python</TITLE>
<LINK REL="stylesheet" HREF="oreillyi/oreillyN.css">
</HEAD>
<BODY bgcolor="white" text="black" link="#990000" vlink="#990000" alink="#990000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" cellpadding=5 cellspacing=0 border=0 class="navtopbg"><tr><td><font size="1"><p class="navtitle"><a href="8.html" class="navtitle">Web Development</a> > <a href="0672319942.html" class="navtitle">Python Developer's Handbook</a> > <a href="227.html" class="navtitle">17. Development Tools</a> > <span class="nonavtitle">Profiling Python</span></p></font></td><td align="right" valign="top" nowrap><font size="1"><a href="main.asp?list" class="safnavoff">See All Titles</a></font></td></tr></table>
<TABLE width=100% bgcolor=white border=0 cellspacing=0 cellpadding=5><TR><TD>
<TABLE border=0 width="100%" cellspacing=0 cellpadding=0><TR><td align=left width="15%" class="headingsubbarbg"><a href="235.html" title="Debugging the Application"><font size="1">< BACK</font></a></td><td align=center width="70%" class="headingsubbarbg"><font size="1"><a href="popanote.asp?pubui=oreilly&bookname=0672319942&snode=236" target="_blank" title="Make a public or private annnotation">Make Note</a> | <a href="236.html" title="Use a Safari bookmark to remember this section">Bookmark</a></font></td><td align=right width="15%" class="headingsubbarbg"><a href="237.html" title="Distributing Python Applications"><font size="1">CONTINUE ></font></a></td></TR></TABLE>
<a href="6%2F1%2F2002+6%3A22%3A43+PM.html" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><font color=white size=1>152015024128143245168232148039196038240039088173205162105045222218066183096102193043092</font><a href="read4.asp?bookname=0672319942&snode=236&now=6%2F1%2F2002+6%3A22%3A43+PM" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><br>
<FONT>
<h3>
Profiling Python</h3>
<p>Profiling an application means to be able to sketch an image about what is going on behind the scenes when you execute a program.</p>
<P>The <A NAme="idx1073750400"></a>
<a NAME="idx1073750401"></a>
<tt cLASS="monofont">sys</tt> module is able to perform a very simple profiling task by telling you a little bit about what is going on after each function, method, or specific line gets executed.</p>
<blockquote>
<p><a name="idx1073750402"></a><A naMe="idx1073750403"></a>
<p><Tt claSs="monofont">sys.setprofiler(profiler_function)</tt>棤
This function implements a source code profiler, which identifies a function that must be executed whenever a function or method is called.</P>
</P>
<P>
<A name="idx1073750404"></A>
<A NAme="idx1073750405"></a>
<p><TT CLass="monofont">sys.settrace(tracer_function)</tT>棤
The functionality of this function is basically the same one of the <A NAme="idx1073750406"></a>
<a name="idx1073750407"></a>
<tt class="monofont">setprofiler()</tt> function. However, this one is called whenever a new line is executed.</p>
</p>
</BloCkquOte>
<prE>
>>> import sys
>>> def profiler(frame, event, arguments):
... print frame.f_code.co_name, frame.f_lineno, event, arguments
...
>>> sys.setprofile(profiler)
? 1 return None
>>> lst = ["Spam","Parrot","Knights"]
? 1 call None
? 1 return None
>>> def showlist(_lst):
... for l in _lst:
... print l
... return _lst
...
? 1 call None
? 1 return None
>>> showlist(lst)
? 1 call None
showlist 1 call None
Spam
Parrot
Knights
showlist 4 return ['Spam', 'Parrot', 'Knights']
['Spam', 'Parrot', 'Knights']
? 1 return None
>>> sys.setprofile(None)
</pre>
<P>If you really want to perform a more complete and accurate study, you need to use the <TT Class="monofont">profiler</TT> module.</P>
<H4>Python Profiler</h4>
<p>The information provided here offers a brief overview about how to use the <a nAME="idx1073750408"></A>
<a namE="idx1073750409"></A>
<TT class="monofont">profile</tt> module to perform the analysis of the run time performance of a Python program. The original <tt class="monofont">profile</tt> module was written by <a namE="idx1073750410"></a>Sjoerd Mullender, and later <a Name="idx1073750411"></A>Guido van Rossum applied some changes to it. All the original documentation is copyrighted by <a namE="idx1073750412"></a>James Roskind (see copyright note in <a hREF="274.html">Appendix C, "Python Copyright Notices)"
</A> , and reproduced here with slight modifications.</p>
<div CLASs="note"><p clASS="notetitle"><B>Note</b></p><p>
<p>Check out the module's original documentation for more information about its "deterministic profiling" implementation.</P>
</P></DIv>
<br>
<br>
<p>You have two possible ways to use the <tt class="monofont">profile</tt> module. The first option is to import it, and make it call a function on your program that you want to analyze, such as</p>
<pre>
import profile
def main():
for n in xrange(100):
print n,
profile.run("main()")
</pRe>
<p>The <A namE="idx1073750413"></a>
<a naMe="idx1073750414"></a>
<a NAME="idx1073750415"></a>
<tt cLASS="monofont">run()</tt> function generates a profiling report that can be manipulated using the <tt CLASs="monofont">pstats</tt> module (the report generating functions are in the <tT CLAss="monofont">pstats</tt> module).</p>
<p>The second option is to invoke the profiler as a main program and pass the script that needs to be profiled as an argument.</p>
<pre>
python profile.py scriptfile [arg...]
</pre>
<p>Next, you have the static member functions that are available for the profiler class. Note that an instance of <tt clasS="monofont">Profile()</tt> is <I>not</i> needed to call them.</p>
<p>To profile an application with a main entry point of <A name="idx1073750416"></A>
<a naME="idx1073750417"></A>
<Tt claSS="monofont">foo(),</TT> you would add the following to your module:</p>
<pre>
import profile
profile.run("foo()")
</PRE>
<P>The previous action would cause <tt clASS="monofont">foo()</Tt> to be run, and a series of informative lines (the profile) to be printed. This approach is most useful when working with the interpreter. If you would like to save the results of a profile into a file for later examination, you can supply a filename as the second argument to the <tt class="monofont">run()</tt> function:<a name="idx1073750418"></a>
<a namE="idx1073750419"></a>
<a Name="idx1073750420"></A>
<a namE="idx1073750421"></a>
</p>
<pRE>
import profile
profile.run("foo()", 'fooprof')
</PRe>
<p>The primary entry point for the profiler is the global function <a nAME="idx1073750422"></A>
<a namE="idx1073750423"></A>
<TT clasS="monofont">profile.run().</TT> It is typically used to create any profile information. The reports are formatted and printed using methods for the class <A name="idx1073750424"></a>
<a name="idx1073750425"></a>
<tt class="monofont">pstats.Stats.</tt> The following is a description of all these standard entry points and functions. For a more in-depth view of some of the code, consider reading the later section on "Extensions: Deriving Better Profilers," which includes a discussion of how to derive better profilers from the classes presented, or reading the source code for these modules.</P>
<p><tAble BordeR="1" celLSPAcing="0" CELLpaddING="1" Width="100%">
<COLGroup align="left" span="2">
<tr valigN="top">
<td>
<Font Size="2">FUNCTION</fOnt></tD>
<TD>
<Font sIZE="2">profile.run(string, filename_opt)</Font></tD>
</TR>
</ColgrOUP>
</Table></p>
<p>This function takes a single argument that can be passed to the <a name="idx1073750426"></a>
<a name="idx1073750427"></a>
<tt ClaSs="monofont">exec</tt> statement, and an optional filename. In all cases, this routine attempts to <Tt claSs="monofont">exec</tt> its first argument, and gathers profiling statistics from the execution. If no filename is present, this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line. The following is a typical output from such a call:</P>
<PRE>
main()
2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
...
</pre>
<p>The first line indicates that this profile was generated by the call: <TT CLass="monofont">profile.run('main()'),</tT> and hence the executed string is <TT Class="monofont">'main()'</TT>. The second line indicates that 2706 calls were monitored. Of those calls, 2004 were <I>primitive</I>. We define primitive to mean that the call was not induced via recursion. The next line, <tt class="monofont">Ordered by: standard name,</tt> indicates that the text string in the far right column was used to sort the output. The <a name="idx1073750428"></a>
<a name="idx1073750429"></A>column headings include</p>
<bLockQuote>
<P>
<p>
<a nAME="idx1073750430"></A>
<tt clASS="monofont">ncalls</Tt> stands for the number of calls.</p>
</p>
<p>
<P>
<A NAme="idx1073750431"></a>
<tT CLAss="monofont">tottime</tt> stands for the total time spent in the given function (and excluding time made in calls to sub-functions).</p>
</p>
<p>
<p>
<a name="idx1073750432"></a>
<tt clasS="monofont">percall</tt> is the quotient of <Tt clAss="monofont">tottime</tt> divided by <Tt clASS="monofont">ncalls.</Tt>
</p>
</p>
<p>
<P>
<A NAme="idx1073750433"></a>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?