Use Xhprof for online PHP performance tracking and analysis

Source: Internet
Author: User
Tags install mongodb mcrypt
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 RE Start You can then pass Phpinfo ()Check 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 you can http://localhost/xhprof/Access, then access http://localhost/xhprof/examples/sample.phpYou can see some output and prompt by accessing the /HTTP /index.php?run=xxx&source=xhprof_fooView the results. Next visit http://localhost/xhprof/xhprof_html/You can see the results that have been saved, listing the calls to all the functions and the time spent.

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

//Open Xhprof and start recordingXhprof_enable (); //Run some functionsFoo (); //Stop recording and fetch results $xhprof _data= Xhprof_disable (); $xhprof _dataAll the function call time and CPU memory consumption in the program step running process are recorded, and the specific metrics can be recorded by Xhprof_enableControl of the ingress parameters, and the subsequent processing has nothing to do with the xhprof extension, roughly writing a storage class Xhprofruns_defaultWill $xhprof _dataSerialized and saved to a directory, you can Xhprofruns_default (__dir__)Outputs the result to the current directory and, if not specified, reads the php.ini configuration file. Xhprof.output_dir, which is still not specified, is output to /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, with the project comes with the sample.phpAs an example, the sample writes a Main ()Function Main ()function is called in the Foo ()、 Bar ()Some sub-functions are processed with a bit of character. During the entire program run, Main ()function has only been run once, and because Main ()All the logic is included in the function, so Main ()The iwall% ratio of the function is 100%, but because Main ()Functions are implemented by a child function, so Main ()The ewall% of the function is only 0.3%, and Foo ()The function completes 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 xhprof_html/index.phpYou can also see the [View full CallGraph]Link, click can draw a visualization of the performance analysis diagram, if you click on the error, may be a lack of dependency Graphviz, Ubuntu can be installed via 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

    //Open xhprofXhprof_enable (Xhprof_flags_memory | XHPROF_FLAGS_CPU); //Collect data after the end of the programRegister_shutdown_function ( function() {$xhprof _data = xhprof_disable (); //Let data collection program run in the background if(Function_exists ( ' Fastcgi_finish_request ') {fastcgi_finish_request ();} //Save Xhprof Data...}); However, it is unavoidable to modify the source code of the project, in fact, PHP itself provides a better way to inject, such as the above logic saved as /opt/inject.php, and then modify the PHP fpm configuration file

    Vi/etc/php5/fpm/php.ini Modify Auto_prepend_fileConfiguration

    auto_prepend_file = /opt/inject.php This will automatically inject all the PHP files that are php-fpm the request. /opt/inject.phpFile

    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

    Cd/opt/htdocsgit CloneHttps //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 Xhprof/setup/database.sql

    Configuration file config.inc.phpNeed to adjust in

  • ' Url_base ' = ' http://localhost/xhprof.io/', which is the path of the Xhprof.io interface
  • ' PDO ' = new PDO (' Mysql:dbname=xhprof;host=localhost;charset=utf8 ', ' root ', ' password '), adjust configuration according to MySQL situation
  • Enable this is an anonymous function that enables XHPROF data collection when the anonymous function returns True
  • by configuring EnableThe need for online debugging, such as

    Always Turn on xhprof

    ' Enable '= function() { return true;} 1/100 probability random Open xhprof

    ' Enable '= function() { returnRand 0, -) === 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 () { returnStrpos ( $_server[ ' Request_uri '], '/testurl ') === 0;} Finally, as described above, the project to be configured contains xhprof.io/inc/inject.phpCan.

    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

    Apt-get Install MongoDB Php5-mongo php5-mcryptcp/etc/php5/mods-available/mcrypt.ini/etc/php5/fpm/conf.d/cp/etc/ Php5/mods-available/mcrypt.ini/etc/php5/cli/conf.d/cd/opt/htdocsgit CloneHttps //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 Precourier new ', monospace; font-size:13px; Color:rgb (51,51,51); line-height:20px; Word-break:break-all; Word-wrap:break-word; White-space:pre-wrap; Background-color:rgb (245,245,245) "> MONGO US e xhprof;db.dropdatabase ();

    The above describes the use of Xhprof for online PHP performance tracking and analysis, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • 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.