前言
最近在整理优化项目响应时间过长的API接口,最初使用加时间戳写入日志的方法,凭感觉查看那一块代码耗时,遇到mysql还需要开启sql::query把耗时语句写入日志,耗时耗力。在网上找了一个性能分析项目 tideways + xhgui,安装好tideways扩展后,直接在php.ini文件增加参数auto_prepend_file,就可以手机日志,并请不用改自己项目代码。
安装扩展
tideways收集耗时日志写入mongo,所以需要下提前按装MongoDB和mongodb.so扩展,也可以自己往mongo写数据,不用pre_append_php机制或者include xhgui的header.php
- mongo.so
wget https://pecl.php.net/get/mongodb-1.7.4.tgz
tar -zxvf mongodb-1.7.4.tgz
cd mongodb-1.7.4
phpize
./configure
make && make install
2.tideways.so
git clone https://github.com/tideways/php-xhprof-extension.git
cd php-xhprof-extension
git checkout v4.1.7
phpize
./configure
make && make install
- 修改php.ini配置,引入mongodb、tideways扩展
extension=mongodb.so
[tideways]
extension=tideways.so
; 不需要自动加载,在程序中控制就行
tideways.auto_prepend_library=0
; 频率设置为100,在程序调用时可以修改
tideways.sample_rate=100
- xhgui-branch项目会读取MongoDB日志并以非常友好的界面展示出来
git clone https://github.com/laynefyc/xhgui-branch.git
php install.php
# 修改 xhgui-branch/config/config.default.php 配置文件
# 1. 默认支持的扩展是xhprof
# 'extension' => 'tideways',
# 2. 修改mongodb数据库连接
#'db.host' => 'mongodb://127.0.0.1:27017',
- 再次修改php.ini文件
# 每次php程序执行完毕以后会自动调用下面的php文件
auto_prepend_file="你的项目地址/xhgui-branch/external/header.php"
使用
为xhgui-branch项目部署域名,便于查看统计日志
server {
listen 8000;
server_name localhost;
root 你的项目地址/xhgui-branch/webroot;
location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
localhost:8000即可查看详细日志
名词解释
| 名称 | 含义 |
|---|---|
| Incl. Wall Time (microsec) | 函数运行时间(包括子函数) |
| Excl. Wall Time(microsec) | 函数运行时间(不包括子函数),这里可以倒序,优化消耗时间最高的函数 |
| Incl. CPU(microsecs) | 函数运行CPU(包括子函数) |
| Excl. CPU(microsecs) | 函数运行CPU(不包括子函数 ) |
| Incl.MemUse(bytes) | 函数运行消耗内存(包括子函数) |
| Excl.MemUse(bytes) | 函数运行消耗内存(不包括子函数) |
参考文档
- laravel性能优化建议:segmentfault.com/a/119000001…
- 火焰图看法:www.ruanyifeng.com/blog/2017/0…