Turn: Use xhprof for online PHP performance tracking and analysis

Source: Internet
Author: User

Originally from: Http://avnpc.com/pages/profiler-php-performance-online-by-xhprof

Original Author: allovince

Prior to using PHP based on xdebug performance analysis, for the local development environment is sufficient, but if it is online environment, xdebug consumption, configuration is not flexible, so the online environment is recommended to use the Xhprof PHP performance tracking and analysis.

Installation and simple usage of xhprof

Xhprof is Facebook's open source Lightweight PHP performance analysis tool that can be installed directly in Linux under the pecl, such as just 3 lines of instruction in Ubuntu

pecl install xhprof-betaecho "extension=xhprof.so" > /etc/php5/fpm/conf.d/xhprof.iniservice php5-fpm restart

You can then phpinfo() check to see if the extension is already loaded.

How to use it, the XHPROF project already provides an example and a simple UI, download the XHPROF project to the Web server, assuming http://localhost/xhprof/ that it can be accessed, then access http://localhost/xhprof/examples/sample.php can see some output, and prompt to view the results by accessing http://<xhprof-ui-address>/index.php?run=XXX&source=xhprof_foo . Next http://localhost/xhprof/xhprof_html/ , you will see the saved results, listing the calls to all the functions and the time spent.

Analyzing the sample code sample.php , the key section is only 2 lines:

//开启xhprof并开始记录xhprof_enable();//运行一些函数foo();//停止记录并取到结果$xhprof_data = xhprof_disable();

$xhprof_dataIn the program single-step running process all the function call time and CPU memory consumption, and so on, specifically to record which indicators can be xhprof_enable controlled by the entry parameters, after the processing has not been related to the xhprof extension, basically write a storage class XHProfRuns_Default , will be $xhprof_data serialized and saved to a directory , you can output to the XHProfRuns_Default(__DIR__) current directory by outputting the result, if it is not specified, it will be read in the php.ini configuration file xhprof.output_dir , and still not specified /tmp .

xhprof_html/index.phpOrganize and visualize the results of the records, which are listed in the default UI:

    • Funciton Name: Name of function
    • Calls: Number of calls
    • Incl. Wall time (MICROSEC): function runtime (including child functions)
    • iwall%: Function run time (including sub-function) percentage
    • Excl. Wall time (MICROSEC): function runtime (excluding child functions)
    • ewall%: Function run time (excluding child functions)

Each item should not be difficult to understand, taking the project's own example sample.php , a function is written in the example, the main() main() function calls foo() , bar() and so on, some sub-functions do a bit of character processing. The function only runs once during the whole program, main() and since main() all the logic is included in the function, main() the iwall% ratio of the function is 100%, but since the function main() is implemented by the child function, the function main() 's ewall% Only 0.3%, and the foo() function completed the main work, ewall% has 98.1%. Therefore, in the analysis of larger programs, often need to be based on these indicators are sorted separately, from different angles to examine performance consumption.

In the xhprof_html/index.php can also see [View Full Callgraph] links, click can draw a visualization of the performance analysis diagram, if the error after clicking, may be a lack graphviz of dependency, Ubuntu can be installed through apt

apt-get install graphviz
A better way to inject

Knowing the above, you can already integrate Xhprof into any project that we already have. Most MVC frameworks now have a unique portal file that simply injects xhprof logic at the beginning of the portal file

//开启xhprofxhprof_enable(XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_CPU);//在程序结束后收集数据register_shutdown_function(function() {    $xhprof_data        = xhprof_disable();    //让数据收集程序在后台运行    if (function_exists(‘fastcgi_finish_request‘)) { fastcgi_finish_request(); } //保存xhprof数据 ...});

However, it is unavoidable to modify the source code of the project, in fact, PHP itself provides a better way to inject, such as to save the above logic as /opt/inject.php , and then modify the PHP fpm configuration file

vi /etc/php5/fpm/php.ini

Modify auto_prepend_file Configuration

auto_prepend_file = /opt/inject.php

This will automatically inject the files before all the PHP files that are PHP-FPM requested. /opt/inject.php

If Nginx is used, it can also be set through Nginx configuration file, which is less intrusive and can implement site-based injection.

fastcgi_param PHP_VALUE "auto_prepend_file=/opt/inject.php";
Better analysis tools: Xhprof.io or Xhpgui

After injecting the code, we also need to implement the UI to save the XHPROF data and display the data, which sounds like a lot of work, is there a ready-made wheel to use?

After searching and comparing, it seems that the better choice has Xhprof.io and Xhpgui.

Two projects to do the same thing, all provide the Xhprof data saving function and a set of index presentation data UI, here are some comparison

Xhprof.io

    • ? Years of disrepair
    • ? Save Xhprof data to MySQL
    • ? Support for data indexing of multiple dimensions, such as domain names, URIs, etc.
    • ? function call records complete, kernel-level functions can be displayed
    • ? Cannot open for individual URIs
    • ? Injection is split into two files and xhprof data cannot be collected if the program is forcibly interrupted

Xhgui

    • ? Save Xhprof data to MongoDB
    • ? Domain index is not supported
    • ? The function call record is incomplete and some kernel-level functions (such as intra-extension) cannot be displayed
    • ? There is a configuration file to control the open condition
    • ? Inject only one file
    • ? A dynamic graph of d3.js-based call relationships

Can see in fact two projects are not perfect, relatively xhgui does not support the domain name index for debugging on the line is unbearable, so my final choice is to use Xhprof.io, but their own micro-adjustment, modified version of the Xhprof.io revision support:

    • ? Add on switch configuration, can be opened for individual URI
    • ? The injected file is merged into a
Xhprof.io Fixed version installation and use

The installation and configuration method is as follows, assuming that the Web server root directory is/opt/htdocs

clone https://github.com/EvaEngine/xhprof.io.gitcd xhprof.io/composer installcp xhprof/includes/config.inc.sample.php xhprof/includes/config.inc.php vi xhprof/includes/config.inc.php

Build the Xhprof.io database in MySQL, assuming the database name is xhprof , and then import the Xhprof/setup/database.sql

The configuration file config.inc.php needs to be adjusted

    • ‘url_base‘ => ‘http://localhost/xhprof.io/‘,This is the path where the Xhprof.io interface is located
    • ‘pdo‘ => new PDO(‘mysql:dbname=xhprof;host=localhost;charset=utf8‘, ‘root‘, ‘password‘),Adjust configuration according to MySQL situation
    • enableThis is an anonymous function that enables XHPROF data collection when the anonymous function returns True

By configuring enable items, you can implement the requirements for online debugging, such as

Always Turn on xhprof

‘enable‘ => function() {    return true;}

1/100 probability random Open xhprof

‘enable‘ => function() {    return rand(0, 100) === 1;}

Web page carrying Parameters debug=1 when opening xhprof

‘enable‘ => function() {    return !empty($_GET[‘debug‘]);}

Web page URL is open when a specific path

‘enable‘ => function() {    return strpos($_SERVER[‘REQUEST_URI‘], ‘/testurl‘) === 0;}

Finally, you can include it in the project you want to configure as described above xhprof.io/inc/inject.php .

Be sure to bold but cautious the online environment, especially if no results are required check whether the xhprof extension is installed .

Appendix: Installation Method of Xhpgui
clone https://github.com/perftools/xhgui.gitcd xhguicomposer installcp config/config.default.php config/config.phpchown www-data.www-data -R cache

Edit Nginx configuration file Join

fastcgi_param PHP_VALUE "auto_prepend_file=/opt/htdocs/xhgui/external/header.php";

You can empty MongoDB when you collect too much data

mongouse xhprof;db.dropDatabase();

Turn: Use xhprof for online PHP performance tracking and analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.