Identify Bottleneck on your PHP Scripts with XDebug Code Trace

XDebug has been around for a while and I have been looking to try its features for a while. This time, I was able to poke around briefly with dumping code traces for my PHP code.

1. Make sure to have XDebug extension installed, you can either do so from your OS package management or build from source. For this exercise I have installed version 2.1.

2. Enable the extension on your PHP configuration file.

; Enable xdebug extension module
zend_extension=/usr/lib64/php/modules/xdebug.so

xdebug.auto_trace = 1
; If you have 2.2, you can enable code trace dumps on demand by adding XDEBUG_TRACE=1 on your URL or as POST variable
;xdebug.trace_enable_trigger = 1
xdebug.trace_output_dir = /var/www/sites/default/xdebug-trace-outputs

3. For the xdebug.trace_output_dir path, make sure it is writable by the HTTP user, in this case I have Apache and the user is, obviously, apache too.

chown apache.revin /var/www/sites/default/xdebug-trace-outputs
chmod 0770 /var/www/sites/default/xdebug-trace-outputs

4. Test your script! Note that every execution or request will generate a code trace dump and by default they will be overwritten. You can set xdebug.trace_options to 1 to create new file per request. Ideally, this is only done on your testing environment 🙂

Here’s a sample output of a code trace:

TRACE START [2013-04-09 13:34:44]
0.0013 651112 -> {main}() /var/www/sites/default/index.php:0
0.0015 651288 -> define() /var/www/sites/default/index.php:2
0.0017 651288 -> define() /var/www/sites/default/index.php:3
0.0017 651288 -> define() /var/www/sites/default/index.php:4
0.0018 651360 -> dirname() /var/www/sites/default/index.php:5
0.0018 651352 -> define() /var/www/sites/default/index.php:5
0.0019 651272 -> error_reporting() /var/www/sites/default/index.php:16
0.0020 651816 -> strpos() /var/www/sites/default/index.php:67
0.0021 651896 -> str_replace() /var/www/sites/default/index.php:77
0.0021 651984 -> pathinfo() /var/www/sites/default/index.php:92
0.0022 651896 -> define() /var/www/sites/default/index.php:92
0.0023 651968 -> define() /var/www/sites/default/index.php:93
0.0023 652088 -> pathinfo() /var/www/sites/default/index.php:94
0.0023 652000 -> define() /var/www/sites/default/index.php:94
0.0024 652032 -> define() /var/www/sites/default/index.php:95
0.0024 651904 -> is_dir() /var/www/sites/default/index.php:97
0.0025 652080 -> define() /var/www/sites/default/index.php:108
...

Enjoy!