Use xhprof to track and analyze online PHP performance

Source: Internet
Author: User
Tags install mongodb
: This article describes how to use xhprof to track and analyze online PHP performance. For more information about PHP tutorials, see. I have been using Xdebug-based PHP for performance analysis. it is enough for the local development environment. However, if it is an online environment, xdebug consumes a lot and the configuration is not flexible enough, therefore, xhprof is recommended for tracking and analyzing PHP performance in the online environment.

Installation and simple usage of xhprof

Xhprof is Facebook's open-source lightweight PHP performance analysis tool. it can be directly installed using pecl in Linux. for example, in Ubuntu, only three lines of commands are required.

Pecl install xhprof-betaecho "extension = xhprof. so">/etc/php5/fpm/conf. d/xhprof. iniservice php5-fpm restart You can use Phpinfo ()Check whether the extension has been loaded.

The xhprof project provides examples and a simple UI to download the xhprof project to the web server. Http: // localhost/xhprof/Access, then access Http: // localhost/xhprof/examples/sample. phpYou can see some output and prompt to access Http :// /Index. php? Run = XXX & source = xhprof_fooView the result. Next visit Http: // localhost/xhprof/xhprof_html/You can see the saved results and list all function calls and the time consumed.

Analyze the sample code Sample. phpThe key part is only two rows:

// Enable xhprof and start recording xhprof_enable (); // run some functions foo (); // stop the record and obtain the result $ xhprof_data = xhprof_disable (); $ Xhprof_dataIt records all the function call times and CPU memory consumption during a single step of the program. Xhprof_enableThe subsequent processing has nothing to do with the xhprof extension, which is roughly a storage class XHProfRuns_Default, Set $ Xhprof_dataSerialized and saved to a directory. XHProfRuns_Default (_ DIR __)Output the result to the current directory. If this parameter is not specified, the system reads Xhprof. output_dirIf it is not specified, it will be output /Tmp.

Xhprof_html/index. phpOrganize and visualize the record results, which are listed in the default UI:

  • Funciton name: function name
  • Cballs: number of calls
  • Incl. Wall Time (microsec): Function running Time (including subfunctions)
  • IWall %: Percentage of function running time (including sub-functions)
  • Excl. Wall Time (microsec): Function running Time (excluding subfunctions)
  • EWall %: Function running time (excluding subfunctions)
  • Each item should not be hard to understand. Sample. phpFor example Main ()Function, Main ()Function call Foo (), Bar ()And other sub-functions. The entire program is running, Main ()The function runs only once, and Main ()The function includes all the logic, so Main ()Function IWall % accounts for 100%, Main ()Functions are implemented by subfunctions. therefore Main ()The EWall % of the function is only 0.3%, while Foo ()The function has completed the main work. EWall % has 98.1%. Therefore, when analyzing larger programs, you often need to sort these indicators separately to view performance consumption from different perspectives.

    In Xhprof_html/index. phpYou can also see [View Full Callgraph]Click the link to create a visual performance analysis diagram. If an error is reported after clicking the link, the dependency may be missing. GraphvizUbuntu can be installed through apt

    Apt-get install graphvizBetter injection methods

    After learning about the above, we can integrate xhprof into any of our existing projects. Currently, most MVC frameworks have unique entry files. you only need to inject xhprof logic at the beginning of the entry file.

    // Enable xhprofxhprof_enable (XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_CPU); // collect data after the program ends register_shutdown_function (function () {$ xhprof_data = xhprof_disable (); // run the data collection program in the background if (function_exists ('fastcgi _ finish_request ') {fastcgi_finish_request ();} // save xhprof data ...}); However, php itself provides a better injection method, such as saving the above logic /Opt/inject. phpAnd then modify the php fpm configuration file.

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

    Auto_prepend_file =/opt/inject. php In this way, all php-fpm requests will be automatically injected before the php file. /Opt/inject. phpFile

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

    Fastcgi_param PHP_VALUE "auto_prepend_file =/opt/inject. php ";Better analysis tools: xhprof. io or xhpgui

    After code injection, we still need to implement the UI for saving xhprof data and displaying data. it sounds like a lot of work. Is there a ready-made wheel to use?

    After searching and comparison, it seems better to choose xhprof. io and xhpgui.

    The two projects have done almost the same thing, both of which provide the xhprof data storage function and a set of index display data UI. Below are some comparisons:

    Xhprof. io

  • ? Out of service
  • ? Save xhprof data to MySQL
  • ? Supports data indexing in multiple dimensions, such as domain name and URI.
  • ? Complete function call records and kernel-level functions
  • ? Cannot be enabled for individual URIs
  • ? The injection is divided into two files. xhprof data cannot be collected if the program is forcibly interrupted.
  • Xhgui

  • ? Save xhprof data to MongoDB
  • ? Domain name index not supported
  • ? Function call records are incomplete, and some kernel-level functions (such as extended functions) cannot be displayed.
  • ? Configuration files allow you to control enabling conditions.
  • ? Only one file is injected.
  • ? Call relationship dynamics based on D3.js
  • We can see that the two projects are not complete. xhgui does not support domain name indexing, which is intolerable for online debugging. Therefore, my final choice is to use xhprof. i/O, but I made a slight adjustment. the modified xhprof. io correction version support:

  • ? Added the enable switch configuration, which can be enabled for individual URIs
  • ? Merge the injection file into one
  • Installation and Use of xhprof. io correction edition

    The installation and configuration methods are as follows. assume that the web server root directory is /Opt/htdocs

    Cd/opt/htdocsgit 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 Create an xhprof. io database in MySQL. assume that the database name is XhprofAnd then import xhprof/setup/database. SQL

    Configuration file Config. inc. phpTo be adjusted

  • 'URL _ base' => 'http: // localhost/xhprof. io /',This is the path of the xhprof. io interface.
  • 'Pdo' => new pdo ('MySQL: dbname = xhprof; host = localhost; charset = utf8', 'root', 'password '),Adjust the configuration according to the actual situation of MySQL
  • EnableThis is an anonymous function. xhprof data collection is enabled when the anonymous function returns true.
  • Configure EnableTo achieve online debugging, such

    Always enable xhprof

    'Enable' => function () {returntrue ;} 1/100 random xhprof enabled

    'Enable' => function () {return rand (0,100) = 1 ;} Xhprof is enabled when debug = 1 is carried on the webpage

    'Enable' => function () {return! Empty ($ _ GET ['debug']);} Enabled when the webpage URL is a specific path

    'Enable' => function () {return strpos ($ _ SERVER ['request _ url'], '/testurl') === 0 ;} Finally, as described above, the project to be configured contains Xhprof. io/inc/inject. phpYou can.

    Make sure that the xhprof extension is installed if no result is returned.

    Appendix: xhpgui installation method

    Apt-get install mongodb php5-mongo php5-mcryptcp/etc/php5/mod-available/mcrypt. ini/etc/php5/fpm/conf. d/cp/etc/php5/mod-available/mcrypt. ini/etc/php5/cli/conf. d/cd/opt/htdocsgit 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 to add

    Fastcgi_param PHP_VALUE "auto_prepend_file =/opt/htdocs/xhgui/external/header. php "; Mongodb can be cleared when too much data is collected.

    Using use xhprof; db. dropDatabase ();

    The above describes how to use xhprof to track and analyze online PHP performance, including some content, and hope to help those who are interested in PHP tutorials.

    Related Article

    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.