擅长:python、mysql、java
<p>值得指出的是,使用profiler只在主线程上工作(默认情况下),如果使用其他线程,则不会从中获取任何信息。这可能有点麻烦,因为在<a href="http://docs.python.org/library/profile.html" rel="noreferrer">profiler documentation</a>中完全没有提到它。</p>
<p>如果您还想分析线程,那么您需要查看文档中的<a href="http://docs.python.org/library/threading.html#threading.setprofile" rel="noreferrer" title="threading.setprofile() function">^{<cd1>} function</a>。</p>
<p>您还可以创建自己的<code>threading.Thread</code>子类来执行此操作:</p>
<pre><code>class ProfiledThread(threading.Thread):
# Overrides threading.Thread.run()
def run(self):
profiler = cProfile.Profile()
try:
return profiler.runcall(threading.Thread.run, self)
finally:
profiler.dump_stats('myprofile-%d.profile' % (self.ident,))
</code></pre>
<p>使用<code>ProfiledThread</code>类而不是标准类。它可能会给你更多的灵活性,但我不确定它是否值得,特别是如果你使用的第三方代码不使用你的类。</p>