编辑:
这个答案已经在https://github.com/campos-ddc/cprofile_graph实现了
使用 cProfile 进行分析
这是我前段时间写的一篇关于使用 cProfile 进行概要分析的文章。
cProfile 是最常用的 Python 分析器之一,虽然功能非常强大,但标准文本输出有些乏善可陈。在这里,我将向您展示如何以更简单的方式在您的应用程序中使用 cProfile。
使用 cProfile 有两种常用方法,您可以将其用作提示符中的命令来分析给定模块,也可以在代码中使用它来分析代码的特定 sn-ps。
分析模块
要使用 cProfile 分析整个模块,只需在提示符中使用以下命令:
python -m cProfile -o output_filename.pstats path/to/script arg1 arg2
这将使用给定的参数(它们是可选的)运行您的模块并将输出转储到 output_filename.pstats 中。
lots of ways 可以读取该输出文件上的数据,但就本文而言,我们不必担心这些,而是专注于获得图形可视化。
从内部分析
有时您不想分析整个模块,只分析其中的几行。
为此,您必须在模块中添加一些代码。
首先:
import cProfile
然后,您可以将任何代码段替换为以下内容:
cProfile.runctx('Your code here', globals(), locals(), 'output_file')
例如,这是一个分析前后的测试:
import unittest
class Test(unittest.TestCase):
def testSomething(self):
self.DoSomethingIDontCareAbout()
param = 'whatever'
self.RunFunctionIThinkIsSlow(param)
self.AssertSomeStuff() # This is after all, a test
之后:
import unittest
import cProfile
class Test(unittest.TestCase):
def testSomething(self):
self.DoSomethingIDontCareAbout()
param = 'whatever'
cProfile.runctx(
'self.RunFunctionIThinkIsSlow(param)',
globals(),
locals(),
'myProfilingFile.pstats'
)
self.AssertSomeStuff() # This is after all, a test
将 pstats 文件转换为图表
要将分析文件转换为图表,您需要做以下几件事:
下载 gprof2dot 并安装 GraphViz 后,在提示符中运行以下命令:
python gprof2dot -f pstats myProfileFile | dot -Tpng -o image_output.png
您可能必须为 gprof2dot 和/或 dot 使用完整路径,或者您可以将它们添加到 PATH 环境变量中。
在所有这些之后,你应该有一个看起来有点像这样的图像:
较热的颜色(红色、橙色、黄色)表示比较冷的颜色(绿色、蓝色)占用更多总运行时间的函数
在每个节点上,您可以查看该函数使用的总运行时间的百分比以及它被调用的次数。
节点之间的箭头表示哪个函数调用了其他函数,并且这些箭头还有一个标题,表示运行时的百分比是多少。
注意:百分比加起来并不总是 100%,尤其是在引用 C++ 代码的代码部分上,这些代码不会被分析。 cProfile 也无法确定“eval”语句中调用的内容,因此您可能会在图表中看到一些跳跃。