xhprof是facebook团队开发的用于研究php性能的扩展,而且提供了图形化的界面展现性能参数和过程。对于各类php的项目的性能瓶颈研究有必定帮助,值得一用。php
我在上一篇《Dockerfile搭建极简LNMP环境》一文中已经建立好了LNMP环境,下面是基于这个容器进行xhprof的安装和使用。html
编写以下install_xhprof.sh脚本,分为编译安装、设置扩展、部署前端模块文件三大步骤。前端
# get the source codes wget https://pecl.php.net/get/xhprof-2.2.3.tgz tar xvf xhprof-2.2.3.tgz #mv xhprof-2.2.3 xhprof cd xhprof/extension phpize ./configure --enable-xhprof make && make install # enable xhprof in php modules echo "extension=xhprof.so" > /etc/php/7.4/cli/conf.d/20-xhprof.ini echo "xhprof.output_dir=/tmp" >> /etc/php/7.4/cli/conf.d/20-xhprof.ini # enable xhprof in php-fpm modules cp /etc/php/7.4/cli/conf.d/20-xhprof.ini /etc/php/7.4/fpm/conf.d/xhprof.ini # restart php-fpm service service php7.4-fpm restart # move fronted-codes to nginx's path mkdir -p /var/www/xhprof cp -r /installsofts/xhprof/xhprof_html /var/www/xhprof/ cp -r /installsofts/xhprof/xhprof_lib /var/www/xhprof/
server{ listen 80; server_name xhprof.alice.show; location / { root /var/www/xhprof; index index.html index.php; } location ~ \.php$ { root /var/www/xhprof; include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.sock; } }
<?php include_once "./xhprof_lib/utils/xhprof_lib.php"; include_once "./xhprof_lib/utils/xhprof_runs.php"; function test($max) { for ($idx = 0; $idx < $max; $idx++) { echo '2333' . "\r\n"; } } function a() { test(rand(1000,2000)); } // 开启xhprof xhprof_enable(); a(); // 收集profilling数据 $xhprof_data = xhprof_disable(); $xhprof_runs = new XHProfRuns_Default(); $run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo"); # 打印出结果报告的URL echo "\nhttp://xhprof.alice.show/xhprof_html/index.php?run=$run_id&source=xhprof_foo\n";
在浏览器中访问http://xhprof.alice.show/test2.php,就能够看到页面最后打印出了相似输出:
http://xhprof.alice.show/xhprof_html/index.php?run=602c9cfb679ee&source=xhprof_foonginx
而后访问这个连接就能够看到性能报告列表了,其中重点关注Calls(调用次数)以及Excl.Wall Time(执行时间)两列。以下图图1所示,能够看到每一个方法被调用的状况。
此外还提供了调用图,更加直观,如图2所示,红色部分表示耗时很大的环节,也是性能优化须要重点关注的地方。
浏览器
感谢Facebook团队开源出这么好用的性能分析工具,php性能之路还将继续!性能优化