Brendan Gregg的CPU Flame Graphs是一种基于调用堆栈可视化一段时间内的CPU使用情况的方法。
他的FlameGraph github project提供了一种独立于语言的方法来绘制这些图表:
grandparent_func;parent_func;func 42这意味着观察到被检测的程序正在运行函数func,其中从parent_func调用该函数,然后从顶级函数grandparent_func调用该函数。它说调用堆栈被观察了42次。
如何从Python程序中收集堆栈信息并将其提供给FlameGraph?
对于加分:如何扩展才能同时显示C和Python堆栈,甚至是Linux上的内核(类似于Brendan网站上的一些Java和node.js火焰图)?

发布于 2016-05-03 22:54:52
也许您可以尝试一下sys.setprofile,它是标准python分析器profile和cProfile的核心。这个方法为每个函数的"call“和"return”事件设置了一个钩子,包括C-API的那些函数。
settrace系统的配置文件函数的调用方式类似于系统的跟踪函数(请参阅
()),但并不是为每行执行的代码调用该函数(仅在调用和返回时调用,但即使设置了异常也会报告返回事件)。
下面是一个工作示例:
from time import clock
t0 = clock()
def getFun(frame):
code = frame.f_code
return code.co_name+' in '+code.co_filename+':'+str(code.co_firstlineno)
def trace_dispatch(frame, event, arg):
if event in [ "c_call" , 'call', 'return', 'c_return']:
t = int((clock()-t0)*1000)
f = frame
stack=[]
while(f):
stack.insert( 0,getFun(f) )
f = f.f_back
print event, '\t', '; '.join(stack), '; ', t
import sys
sys.setprofile(trace_dispatch)
try:
execfile('test.py')
finally:
sys.setprofile(None)Test.py
def f(x):
return x+1
def main(x):
return f(x)
main(10)这将打印出来
c_call 0
call <module> in test.py:2 ; 1
call <module> in test.py:2; main in test.py:5 ; 1
call <module> in test.py:2; main in test.py:5; f in test.py:2 ; 5
return <module> in test.py:2; main in test.py:5; f in test.py:2 ; 8
return <module> in test.py:2; main in test.py:5 ; 11
return <module> in test.py:2 ; 14
c_return 18
c_call 21请参阅更全面的分析函数here。
python中的C堆栈
您不能在python解释器中访问C堆栈。有必要使用支持C/C++的调试器或分析器。我会推荐gdb python。
发布于 2018-11-03 23:15:56
Pyflame支持以两种格式绘制火焰图形(要么是问题中的“传统”形式,要么是chrome的“横向”火焰图形,使用chrome本身)。
来自https://github.com/uber/pyflame
# Attach to PID 12345 and profile it for 1 second
pyflame -p 12345
# Attach to PID 768 and profile it for 5 seconds, sampling every 0.01 seconds
pyflame -s 5 -r 0.01 -p 768
# Run py.test against tests/, emitting sample data to prof.txt
pyflame -o prof.txt -t py.test tests/https://stackoverflow.com/questions/28000637
复制相似问题