Profile PHP With Xdebug and Webgrind On Ubuntu 16

October 20, 2016

This is a simple tutorial on how to setup Xdebug and use Webgrind on Ubuntu 16.04 LTS to profile PHP code. This tells you right where to look when optimizing and it's configurable so it's not always on (seeing that profiling itself can have a performance impact). See how many times functions are called and how long they are taking before you start optimizing.

First, install the Xdebug PHP extension.

sudo apt-get install php-xdebug

Then, edit /etc/php/7.0/mods-available/xdebug.ini and add the following.

xdebug.profiler_enable = 1
xdebug.profiler_output_name = xdebug.out.%t
xdebug.profiler_output_dir = /tmp
xdebug.profiler_enable_trigger = 1

Now, enable the extension and restart the PHP fpm service and apache.

sudo phpenmod xdebug
sudo service php7.0-fpm restart
sudo service apache2 restart

Now, Xdebug will generate cachegrind files in /tmp that contain non-human readable information about each page load when triggered with the right querystring. To view this information, the tool of choice is Webgrind.

So, lets clone the latest version right into the docroot.

cd /var/www/html
git clone

You might need to install graphviz, which is used by Webgrind for generating graphs.

sudo apt-get install graphviz

Now, load a page on your server you want to profile with your browser, but append ?XDEBUG_PROFILE=1 to the URL. When you visit the page with that querystring, Xdebug will kick in and profile the page resulting in a file under /tmp. You can load as many pages as you want with this querystring and it will generate separate cachegrind files.

Next, open up a new tab or window in your browser and navigate to the URL where you just cloned Webgrind. By default it will look for the files in /tmp and you can simply hit update in the top right corner. This will give you a nice pretty listing of where your code is spending time.

If you're using a database expect anything related to that to be at the top of the list, but you can also see how many queries you're making or if you have any functions that are really expensive before you dive into optimizing. If you're curious how the top level functions get called, you can expand them down and view the entire call graph. Pretty useful information and no more guessing.

Related Posts