如何分析Python脚本?

2024-03-28 21:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行的速度有多快。在Python中,有时方法有点笨拙,即向__main__添加计时代码。

分析Python程序运行多长时间的好方法是什么?


Tags: 方法代码project程序运行编码main时间解决方案
3条回答

值得指出的是,使用profiler只在主线程上工作(默认情况下),如果使用其他线程,则不会从中获取任何信息。这可能有点麻烦,因为在profiler documentation中完全没有提到它。

如果您还想分析线程,那么您需要查看文档中的^{} function

您还可以创建自己的threading.Thread子类来执行此操作:

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,))

使用ProfiledThread类而不是标准类。它可能会给你更多的灵活性,但我不确定它是否值得,特别是如果你使用的第三方代码不使用你的类。

Python包含一个名为cProfile的分析器。它不仅给出了总的运行时间,还分别给出了每个函数的时间,并告诉您每个函数被调用了多少次,从而很容易确定应该在哪里进行优化。

您可以从代码内部或从解释器调用它,如下所示:

import cProfile
cProfile.run('foo()')

更有用的是,您可以在运行脚本时调用cProfile:

python -m cProfile myscript.py

为了更简单,我制作了一个名为“profile.bat”的小批处理文件:

python -m cProfile %1

所以我要做的就是跑:

profile euler048.py

我明白了:

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

编辑:更新了PyCon 2013中一个好的视频资源的链接,标题为 Python Profiling
Also via YouTube

不久前,我制作了^{},它从您的Python代码生成可视化。编辑:我已经将示例更新为使用3.3,这是本文撰写时的最新版本。

pip install pycallgraph和安装GraphViz之后,您可以从命令行运行它:

pycallgraph graphviz -- ./mypythonscript.py

或者,您可以分析代码的特定部分:

from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput

with PyCallGraph(output=GraphvizOutput()):
    code_to_profile()

其中任何一个都将生成类似于下图的pycallgraph.png文件:

enter image description here

相关问题 更多 >