選擇一個工具分析PHP函數調用的資源耗用明細,以圖表化的形式展示,方便優化代碼。php
$ pecl install xhprof-beta
前端
在php.ini引用的extension中添加extension=xhprof.so
git
這裏選擇了xhgui,它的原理是在須要測試性能的腳本前加上PHP的一段代碼,將收集到的性能數據存儲到文件或者mongodb等存儲介質中去。github
$ apt-get install mongodb
mongodb
cd /var/www git clone https://github.com/perftools/xhgui.git cd xhgui php install.php
sudo -u www-data php install.php
安裝的時候出現
the requested PHP extension mongodb is missing from your system
問題是平臺的拓展名爲mongo.so,而composer檢查的是mongodb.so,只要加上--ignore-platform-reqs
composer
若是composer問題不清楚,建議單獨跑composer命令,加上-vvv打開調試模式函數
如前面說的原理是在頭部添加一段PHP代碼,這裏經過在Nginx裏配置,或者PHP ini auto_prepend_file 在php.ini中添加auto_prepend_file 。工具
location ~ \.php { include fastcgi_params; fastcgi_buffers 128 4k; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PHP_VALUE "auto_prepend_file=\"/opt/htdocs/xhgui/external/header.php\""; }
在config目錄下添加config.php配置性能
<?php return array( 'debug' => false, 'mode' => 'development', // Can be either mongodb or file. /* 'save.handler' => 'file', 'save.handler.filename' => dirname(__DIR__) . '/cache/' . 'xhgui.data.' . microtime(true) . '_' . substr(md5($url), 0, 6), */ 'save.handler' => 'mongodb', // Needed for file save handler. Beware of file locking. You can adujst this file path // to reduce locking problems (eg uniqid, time ...) //'save.handler.filename' => __DIR__.'/../data/xhgui_'.date('Ymd').'.dat', 'db.host' => '127.0.0.1:27017', 'db.db' => 'xhprof', // Allows you to pass additional options like replicaSet to MongoClient. // 'username', 'password' and 'db' (where the user is added) 'db.options' => array(), 'templates.path' => dirname(__DIR__) . '/src/templates', 'date.format' => 'M jS H:i:s', 'detail.count' => 6, 'page.limit' => 25, // Profile 1 in 100 requests. // You can return true to profile every request. 'profiler.enable' => function() { return rand(1, 100) === 3; }, 'profiler.simple_url' => function($url) { return preg_replace('/\=\d+/', '', $url); } );