如何逐行分析 Python 代码? [英] How can I profile Python code line-by-line?
问题描述
我一直在使用 cProfile 来分析我的代码,而且效果很好.我还使用 gprof2dot.py 来可视化结果(使它更清晰一些).
I've been using cProfile to profile my code, and it's been working great. I also use gprof2dot.py to visualize the results (makes it a little clearer).
然而,cProfile(以及我目前见过的大多数其他 Python 分析器)似乎只在函数调用级别进行分析.当从不同的地方调用某些函数时,这会导致混乱 - 我不知道调用 #1 还是调用 #2 占用了大部分时间.当所讨论的函数有六层深,从其他七个地方调用时,情况会更糟.
However, cProfile (and most other Python profilers I've seen so far) seem to only profile at the function-call level. This causes confusion when certain functions are called from different places - I have no idea if call #1 or call #2 is taking up the majority of the time. This gets even worse when the function in question is six levels deep, called from seven other places.
如何获得逐行分析?
取而代之的是:
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 确实显示了传输"总时间的多少.到父级,但是当您有一堆层和互连调用时,此连接再次丢失.
cProfile does show how much of the total time "transfers" to the parent, but again this connection is lost when you have a bunch of layers and interconnected calls.
理想情况下,我希望有一个可以解析数据的 GUI,然后向我显示我的源文件,并为每一行指定总时间.像这样:
Ideally, I'd love to have a GUI that would parse through the data, then show me my source file with a total time given to each line. Something like this:
main.py:
a = 1 # 0.0s
result = func(a) # 0.4s
c = 1000 # 0.0s
result = func(c) # 5.0s
然后我就可以点击第二个func(c)"调用以查看该调用中占用时间的内容,与func(a)"分开;称呼.有意义吗?
Then I'd be able to click on the second "func(c)" call to see what's taking up time in that call, separate from the "func(a)" call. Does that make sense?
推荐答案
我相信这就是 Robert Kern 的 line_profiler 用于.来自链接:
I believe that's what Robert Kern's line_profiler is intended for. From the link:
File: pystone.py
Function: Proc2 at line 149
Total time: 0.606656 s
Line # Hits Time Per Hit % Time Line Contents
==============================================================
149 @profile
150 def Proc2(IntParIO):
151 50000 82003 1.6 13.5 IntLoc = IntParIO + 10
152 50000 63162 1.3 10.4 while 1:
153 50000 69065 1.4 11.4 if Char1Glob == 'A':
154 50000 66354 1.3 10.9 IntLoc = IntLoc - 1
155 50000 67263 1.3 11.1 IntParIO = IntLoc - IntGlob
156 50000 65494 1.3 10.8 EnumLoc = Ident1
157 50000 68001 1.4 11.2 if EnumLoc == Ident1:
158 50000 63739 1.3 10.5 break
159 50000 61575 1.2 10.1 return IntParIO
这篇关于如何逐行分析 Python 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!