Xhprof 的配置和使用方法

Xhprof 的配置和使用方法

Xhprof是一个分层PHP性能分析工具。

环境

  • Debian + Nginx + PHP-FPM

依赖

  • phpize
  • 安装方法: apt-get install phpize

下载和安装

wget http://pecl.php.net/get/xhprof-0.9.4.tgz
tar zxf xhprof-0.9.4.tgz
cd xhprof-0.9.4/extension/
sudo phpize
./configure
sudo make
sudo make install
cp xhprof.so [path_to_php_extension]/xhprof.so

配置php.ini

[xhprof]
extension=xhprof.so
xhprof.output_dir=/var/www/xhprof/xhprof_runs/

搭建Xhprof运行环境

cp -a [path_to_xhprof]/xhprof_html /var/www/xhprof/
cp -a [path_to_xhprof]/xhprof_lib /var/www/xhprof/

注入PHP代码

xhprof_enable();
/**
...
要检查的php代码
...
**/
$xhprof_data = xhprof_disable();

// 引入xhprof_lib
include_once "/var/www/xhprof/xhprof_lib/utils/xhprof_lib.php";
include_once "/var/www/xhprof/xhprof_lib/utils/xhprof_runs.php";

$instance = new XHProfRuns_Default();
$run_id = $instance->save_run($xhprof_data, "xhprof");
var_dump($run_id);

查看检查结果

  • 配置Nginx
server {
    listen 80;
    server_name xhprof.test.com;
    root /var/www/xhprof/xhprof_html;
    index index.html index.php;
    location ~ \.php$ {
        fastcgi_pass php_pool;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}
  • 访问 xhprof.test.com

更优雅的方式

  • 新建一个额外的文件 xhprof.inc.php,保存在/var/www/xhprof/目录下
xhprof_enable(XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_CPU);
register_shutdown_function(function() {
    $xhprof_data = xhprof_disable();
    if (function_exists('fastcgi_finish_request')){
        fastcgi_finish_request();
    }
    include_once "/var/www/xhprof/xhprof_lib/utils/xhprof_lib.php";
    include_once "/var/www/xhprof/xhprof_lib/utils/xhprof_runs.php";
    $xhprof_runs = new XHProfRuns_Default();
    $run_id = $xhprof_runs->save_run($xhprof_data, 'xhprof');
    echo 'save xhprof data';
});
  • 利用PHP的自动加载功能,在执行代码前注入此文件,编辑php.ini
auto_prepend_file = /var/www/xhprof/xhprof.inc.php
  • 重启PHP服务

你可能感兴趣的:(Xhprof 的配置和使用方法)