Skip to main content

xhprof的安装|配置|使用

安装xhprof

mac安装

# 查询
pecl search xhprof
# 安装
pecl install xhprof
# 验证
php -i |grep xhprof

ubuntu安装

# 查询
apt search xhprof

php7.3-xhprof/jammy 2.3.10-1+ubuntu22.04.1+deb.sury.org+2 amd64
Hierarchical Profiler for PHP 5.x

php7.4-xhprof/jammy 2.3.10-1+ubuntu22.04.1+deb.sury.org+2 amd64
Hierarchical Profiler for PHP 5.x

php8.0-xhprof/jammy 2.3.10-1+ubuntu22.04.1+deb.sury.org+2 amd64
Hierarchical Profiler for PHP 5.x

php8.1-xhprof/jammy 2.3.10-1+ubuntu22.04.1+deb.sury.org+2 amd64
Hierarchical Profiler for PHP 5.x

php8.2-xhprof/jammy 2.3.10-1+ubuntu22.04.1+deb.sury.org+2 amd64
Hierarchical Profiler for PHP 5.x

# 安装
apt install php8.2-xhprof
# 验证
php -i |grep xhprof

# 如果apt找不到 只能自行下载安装
wget https://launchpad.net/~ondrej/+archive/ubuntu/php/+build/30132360/+files/php8.2-xhprof_2.3.10-1+ubuntu22.04.1+deb.sury.org+2_amd64.deb
dpkg -i php8.2-xhprof_2.3.10-1tubuntu22.04.1+deb.sury.org+2_amd64.deb

配置xhprof

# 在php.ini中配置【xhprof】模块
[xhprof]
;默认全局开启,也可以在项目中通过xhprof_enable 和 xhprof_disable手动开启和关闭
;xhprof.collect_additional_info = 1
;日志输出目录:xhprof_runs->save_run() 保存时的目录,也是xhprof_html 查看报表的报表目录
xhprof.output_dir="/var/log/xhprof"

使用xhprof

手动采集

# 在代码中手动开启和采集xhprof
# 1 开始采集
xhprof_enable();
# 2 执行任务代码
...
# 3 完成采集,存储数据
$data = xhprof_disable();
file_put_contents('/var/log/xhprof/src_' . uniqid() . '.json', json_encode($data)); // 存到文件(json 格式方便解析)

自动采集

# 只需要在php.ini配置中,设置xhprof.collect_additional_info = 1 即可

本地解析采集数据

// 引入 xhprof_lib
include_once "./xhprof_lib/utils/xhprof_lib.php";
include_once "./xhprof_lib/utils/xhprof_runs.php";
// 使用默认存储方式 (文件存储)
$xhprof_runs = new XHProfRuns_Default("/var/log/xhprof");
// 保存结果,返回 run id
$data = json_decode(file_get_contents('/var/log/xhprof/src_68ccf03318f87.json'), true);
$run_id = $xhprof_runs->save_run($data, "hellochat");
echo "xhprof run id: $run_id\n";

本地解析查看报表

# 查询
cd /xhprof/xhprof_html && php -S 0.0.0.0:8082