使用xhprof分析php代码性能

时间:2023-03-09 18:50:18
使用xhprof分析php代码性能

推荐在Linux平台使用xhprof,win下xhprof目前稳定版本在php5.5

安装xhprof

下载地址 http://pecl.php.net/get/xhprof-0.9.4.tgz

与php其他扩展安装方式一致 见:http://www.cnblogs.com/web21/p/6007318.html

配置php.ini

[xhprof]
extension=php_xhprof.dll
xhprof.output_dir=/tmp  ;;设置性能分析数据存放位置

测试代码

<?php

// Created by YangShaoXiang on 2016/11/24.

/*

* 结果类似如下...

* [main()==>str_repeat] => Array(

  1. [ct] => 999        //str_repeat这个函数被调用了999次
  2. [wt] => 201      //每次运行str_repeat所要的时间,不知道这个是不是平均值
  3. [cpu] => 0      //每次运行str_repeat,cpu运算时间
  4. [mu] => 520904 //每次运行str_repeat,php所使用内存的改变
  5. [pmu] => 512104       //每次运行str_repeat,php在内存使用最高峰时,所使用内存的改变

* )

...
*/

xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
for ($byte = 1; $byte < 1000; $byte++) {
$arr[] = str_repeat('=', $byte);
test(1, 5);
}

function test($v1, $v2)
{
return $v1 * $v2;
}

$xhp_data = xhprof_disable();

print_r($xhp_data);

  1. [ct] => 5       //bar()这个函数被调用了5次
  2. [wt] => 63      //每次运行bar()所要的时间,不知道这个是不是平均值
  3. [cpu] => 0      //每次运行bar(),cpu运算时间
  4. [mu] => 2860    //每次运行bar(),php所使用内存的改变
  5. [pmu] => 0      //每次运行bar(),php在内存使用最高峰时,所使用内存的改变