23

记一个cpu被PHP函数打爆的坑(xhprof的使用)

 5 years ago
source link: https://div.io/topic/2199?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

背景

最近2月把wise feed后端重构了一次,上线一周了,但一直没放量, 原因是压测太耗CPU,2G 4核的实例连50qps扛不住。

最初性能

50qps CPU直接消耗150%

IbUVNrY.png!web

xhprof安装(hhvm引擎) 具体见下一篇

问题一:IP定位

JJv2Mzn.png!weba2qYzaE.png!web 找到函数,并查看相关功能(每次请求都会调用ip转地址函数,此函数会读文件) z2ARBrV.png!web 查看文件大小,很显然是每次请求读大文件所致 7JjuaiU.png!web

修复方案:

1)调用lbs高精度定位服务,资源成本高,频繁更新;

2) hhvm扩展,启动时一次加载到内存

综合考虑选择了第二种方案, 上线后压测 cpu消耗降到了 110% Vb67Nz7.png!web

问题二: 前端渲染

很显然是 渲染前端模版smarty文件校验的问题

y2iENbf.png!web

bEbemeF.png!web

修复问题后,最终性能:

MF3Uv2M.png!web

u6FBJjJ.png!web

xhprof安装

1. 下载xhprof工具包到webroot

cd ~/orp/webroot

wget -nv ' ftp://xxxxx/tools/perftool/perftool_1-0-2_BL/output/perftool.tar.gz ' //自己官网下载

tar xzf perftool.tar.gz

2. 开启xhprof

若是hhvm引擎,修改hhvm/conf/hhvm.hdf,开启xhprof开关,并重启hhvm ``

Stats {

EnableHotProfiler = true }

若是PHP,修改php/etc/ext/xhprof.ini,并重启php-cgi

[xhprof]

extension="xhprof.so"

3. 在项目模块入口打开xhprof开关,如 webroot/xx模块/index.php

require_once( 'home/work/xxx/xhprof/include.php');

XHProf::enable();

// 下面是你的代码逻辑

4. 请求你的服务

在 orp/data/xhprof会生成相关性能数据

5. 配置并查看可视化的监控数据

启nginx 一个server 并配置转发到 xhprof

如: rewrite ^/perftool(/[^\?] )?((\?. )?)$ /perftool/xhprof/xhprof_html/index.php$1$2 break;

NZJZjiF.png!web 根据请求时间,查看详细的数据: qaQNFrF.png!web

6.其他用法

-> xhprof默认是统计函数的执行时间,如果要统计cpu消耗或内存消耗可以传flags: XHProf::enable(XHPROF FLAGS CPU | XHPROF FLAGS MEMORY)

-> 要分析ral调用细节,可以传参数指定ral日志所在的路径:XHProf::enable(0, array('ral_log' => ROOT_PATH . '/log/worker'));

-> 只想对一部分代码进行分析,可以在执行这段代码前调用XHProf::enable,执行后调用XHprof::disable。

7.官网 http://php.net/manual/zh/book.xhprof.php


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK