我一直在使用cProfile来分析我的代码,而且效果很好。我还使用gprof2dot.py将结果可视化(使其更加清晰)
然而,cProfile(以及我到目前为止看到的大多数其他Python分析器)似乎只在函数调用级别进行分析。当从不同的地方调用某些函数时,这会导致混乱-我不知道调用1或调用2占用了大部分时间。当所讨论的函数有六层深,从其他七个地方调用时,情况会变得更糟
如何获得逐行分析
与此相反:
function #12, total time: 2.0s
我想看看这样的东西:
function #12 (called from somefile.py:102) 0.5s
function #12 (called from main.py:12) 1.5s
cProfile确实显示了有多少总时间“传输”到父级,但是当您有一堆层和互连调用时,这种连接再次丢失
理想情况下,我希望有一个GUI来解析数据,然后向我显示我的源文件以及每行的总时间。大概是这样的:
main.py:
a = 1 # 0.0s
result = func(a) # 0.4s
c = 1000 # 0.0s
result = func(c) # 5.0s
然后,我可以点击第二个“func(c)”调用,查看该调用占用的时间,与“func(a)”调用不同。这有意义吗
我相信这就是Robert Kern's line_profiler的目的。从链接:
为此,您可以使用line_profiler软件包
1。第一次安装软件包:
2。使用magic命令将包加载到python/notebook环境中
3。如果要分析函数的代码,则
执行以下操作:
如果遵循以下步骤,您将获得一个包含所有详细信息的格式良好的输出:)
您也可以使用pprofile(pypi)。 如果要评测整个执行,则不需要修改源代码。 您还可以通过两种方式分析较大程序的子集:
在到达代码中的特定点时切换分析,例如:
通过使用统计分析,从调用堆栈异步切换分析(需要在考虑的应用程序中触发此代码的方法,例如信号处理程序或可用工作线程):
代码注释输出格式与line profiler非常相似:
请注意,因为pprofile不依赖于代码修改,所以它可以分析顶级模块语句,允许分析程序启动时间(导入模块、初始化全局函数等所需的时间)
它可以生成cachegrind格式的输出,因此您可以使用kcachegrind轻松浏览大型结果
披露:我是档案作者
相关问题 更多 >
编程相关推荐