facebook,做为世界上最大的php应用网站,为php贡献出了hhvm xhprof等优秀开源工具,其中xhprof已成为很多phper调试php性能瓶颈的利器。本文作者将从xhprof源码出发,看看xhprof是怎么做到性能分析的
关键数据结构
xhprof主要只使用了如下两个数据结构:
xhprof的两种分析模式
1、XHPROF_MODE_HIERARCHICAL模式,该模式是详细分析整个PHP代码的执行情况,其输出的分析数据如下:
array(7){["main()==>load::./inc.php"]=>array(5){……}["main()==>run_init::Test/inc.php"]=>array(5){……}["bar==>echoHello"]=>array(5){……}["foo==>bar"]=>array(5){……}["main()==>foo"]=>array(5){……}["main()==>xhprof_disable"]=>array(5){……}["main()"]=>array(5){["ct"]=>int(1)["wt"]=>int(390372)["cpu"]=>int(392000)["mu"]=>int(15040)["pmu"]=>int(10024)}}
2、XHPROF_MODE_SAMPLED模式,该模式每隔0.1秒取样一次,记录当前执行的堆栈,其输出的分析数据如下:
array(5){["1460294938.300000"]=>string(30)
"main()==>foo==>bar==>echoHello"["1460294938.400000"]=>string(30)
"main()==>foo==>bar==>echoHello"["1460294938.500000"]=>string(30)
"main()==>foo==>bar==>echoHello"["1460294938.600000"]=>string(30)
"main()==>foo==>bar==>echoHello"["1460294938.700000"]=>string(30)
"main()==>foo==>bar==>echoHello"
}
该模式通过使用xhprof-flamegraphs和FlameGraph可生成flame graph,如下图(我的测试代码的图太简陋,就用xhprof-flamegraphs的图代之了= =):
XHPROF_MODE_HIERARCHICAL模式分析
一、xhprof_enable([ int $flags = 0 [, array $options ]] )的第二个参数$options用于过滤掉不想被profile的函数,过滤函数功能的实现:
1、在xhprof_enable()中会先执行:hp_get_ignored_functions_from_arg(optional_array),将要忽略的函数存储到char **hp_globals.ignored_function_names中。
2、接着执行hp_ignored_functions_filter_init()初始化uint8 hp_globals.ignored_function_filter[XHPROF_IGNORED_FUNCTION_FILTER_SIZE],具体代码如下:
static
void
hp_ignored_functions_filter_init(){
if(hp_globals.ignored_function_names
!=NULL){inti=0;for(;
hp_globals.ignored_function_names[i]
!=NULL;
i++){char*str=