Tuesday, April 27, 2010

Profile php code with xdebug for fast performance

There are times when we need to look into the execution path of php. We need to find out what is going under the hood of php, What and how many objects are created, What function take most time to execute.

This is where xdebug extension for php come handy. Xdebug 2 is a most important extension for a php programmer as it provides various ways of debugging and analysing your code on your development server. The installation of xdebug is very easy. I am going to show how it can be installed and enabled it in xampp for windows, but installation on other OS is same.

xampp already comes with xdebug, but that not work for me, so I download a new dll for xdebug.org. Once you have the dll, follow the given steps to install it :

1. copy the xdebug dll in php ext folder.

2. edit the php.ini (one that resides in apache bin folder)

a. comment out any other zend_extension entries
b add following configuration

[XDebug]
zend_extension_ts = "C:\xampp\php\ext\php_xdebug-2.0.0-5.2.2.dll"
xdebug.remote_enable=On
xdebug.remote_host="localhost"
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.profiler_enable=1
xdebug.profiler_output_name=cachegrind.out.%t
xdebug.profiler_output_dir="C:\xampp\tmp"

3. restart apache

4. confirm that xdebug is enabled using phpinfo();

The above configuration will create a profile dump file for each request. If you don't want to create this file for each request, You can also selectively enable the profiler with the xdebug.profiler_enable_trigger setting set to 1. If it is set to 1, then you can enable the profiler by using a GET/POST or COOKIE variable of the name XDEBUG_PROFILE. The FireFox 2 extension that can be used to enable the debugger (see HTTP Debug Sessions) can also be used with this setting. In order for the trigger to work properly, xdebug.profiler_enable needs to be set to 0.

View the Cachegrind files:

WinCacheGrind is the best way to get useful information out of your cachegrind output file on windows (Linux users can use KCachegrind) . It provides a simple tree view of the PHP execution with references to class, function and filenames. Most importantly, it tells you how long each function call took.

For more information on configuration of xdebug, visit http://xdebug.org/docs/profiler