繁体   English   中英

适用于Python的CPU火焰图

[英]CPU Flame Graphs for Python

Brendan Gregg的CPU火焰图是一种基于调用堆栈可视化一段时间内CPU使用率的方法。

他的FlameGraph github项目提供了一种独立于语言的方式来绘制这些图:

对于每种语言,FlameGraph都需要一种以如下行形式提供堆栈输入的方法:

grandparent_func;parent_func;func 42

这意味着观察到已检测程序正在运行函数func ,该函数从parent_func调用,又从顶级函数grandparent_func调用。 它说已观察到调用堆栈42次。

如何从Python程序收集堆栈信息并将其提供给FlameGraph?

值得一提的是:如何扩展它才能显示C和Python堆栈,甚至显示到Linux上的内核(类似于布伦丹网站上的Java和node.js火焰图)?

在此处输入图片说明

也许您可以尝试sys.setprofile ,它是标准python profiler profilecProfile 此方法为每个函数(包括C-API的那些函数)的“调用”和“返回”事件设置一个钩子。

系统的配置文件函数的调用与系统的跟踪函数类似(请参阅settrace()),但是不会为每个已执行的代码行调用(仅在调用和返回时),即使已发生异常,也会报告return事件组)。

下面是一个工作示例:

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)

测试文件

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

在此处查看更全面的分析功能。

python中的C堆栈

您无法在python解释器中访问C堆栈。 必须使用支持C / C ++的调试器或探查器。 我会建议gdb python

Pyflame支持以两种格式绘制火焰图(问题中的“传统”形式或使用铬本身的chrome的“ sideside”火焰图)。

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM