To profile my php applications I used xdebug in combination with webgrind in the past. Webgrind visualizes the cachegrind files generated by xdebug. This approach is ok but webgrind only contains basic visualization features.

After some research I ended up with a tool called Xhprof. But Xhprof does not have a version for PHP 7.x. So I looked for an alternative and found the cloud service tideways.io that provides a profiler extension that is compatible with Xhprof and is available for free.

In this article I want to share my learnings during the installation of the profiler and XHGui and also want to show how to start profiling your web application.

Installing Tideways profiler

brew tap tideways/homebrew-profiler
brew install php71-tideways --env=std

Without the env option I always got a compilation error saying that php.h is not available. (See https://github.com/tideways/homebrew-profiler for more details)

Installing XHGui

XHGui is a simple php application that can be installed with composer. Execute the following steps to get the current version of XHGui.

git clone https://github.com/perftools/xhgui.git
cd xhgui
php install.php

Install mongodb

brew install mongodb
brew install php71-mongodb

To optimize the mongodb query performance you should run the following optimizations in your shell.

mongo

use xhprof
db.results.ensureIndex( { 'meta.SERVER.REQUEST_TIME' : -1 } )
db.results.ensureIndex( { 'profile.main().wt' : -1 } )
db.results.ensureIndex( { 'profile.main().mu' : -1 } )
db.results.ensureIndex( { 'profile.main().cpu' : -1 } )
db.results.ensureIndex( { 'meta.url' : 1 } )

Starting XHGui

For demonstration purposes I use the PHP built-in webserver but you can also use any other webserver.

php -S localhost:9999 -t webroot/

Starting your Application with profiling

To enable profiling you need to include a so called prepend_file to each php call. This can be done via the auto_prepend_file parameter. For configuring Apache or Nginx please read the Profile an Application or Site section of the XHGui documentation.

php -S localhost:8080 -dauto_prepend_file=/path/to/xhgui/external/header.php

Configure the profiling rate

XHGui allows you to define when to enable the profiler. This can be done in a closure inside the config/config.php file.

Profile every request

return array(
    // Other config
    'profiler.enable' => function() {
        return true;
    }
);

Profile one out of 100 requests

return array(
    // Other config
    'profiler.enable' => function() {
        return rand(1, 100) === 50;
    }
);

Wrap-Up

With the installation & configuration in place you will be able to profile your application’s performance during development. In a future blog post I will show you how to analyze and debug your application performance with XHGui.

Resources