我一直在使用cProfile来分析我的代码,它工作得很好。我还使用gprof2dot.py来可视化结果(使结果更清晰)。
然而,cProfile(和我迄今为止看到的大多数其他Python剖析器)似乎只在函数调用级别进行剖析。当从不同的地方调用某些函数时,这会导致混乱——我不知道call#1或call#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的目的。从链接:
希望能有帮助!
您也可以使用pprofile(pypi)。 如果要分析整个执行过程,则不需要修改源代码。 您还可以通过两种方式分析较大程序的子集:
在到达代码中的特定点时切换分析,例如:
通过使用统计分析从调用堆栈异步切换分析(需要在考虑的应用程序中触发此代码的方法,例如信号处理程序或可用的工作线程):
代码注释输出格式非常类似于line profiler:
请注意,由于pprofile不依赖于代码修改,因此它可以分析顶级模块语句,从而可以分析程序启动时间(导入模块、初始化globals等所需的时间)。
它可以生成cachegrind格式的输出,因此可以使用kcachegrind轻松浏览大型结果。
披露:我是一个合适的作者。
您可以使用line_profiler软件包来完成此操作
1。首先安装软件包:
2。使用magic命令将包加载到python/notebook环境中
3。如果要分析函数的代码,则
请执行以下操作:%lprun-f函数名函数调用
如果遵循以下步骤,您将获得一个格式良好的输出,其中包含所有详细信息:)
相关问题 更多 >
编程相关推荐