In my posting about installing a PHP development environment using Ubuntu 10.04 I mentioned the possibility to debug PHP code using XDebug and CacheGrind. Here is a little tutorial on howto use profiling with some free open source tools.
Installation / Configuration
XDebug is a debugging component which can be added as a module to PHP using PECL. To install XDebug (if you havent’t used my tutorial yet) simply use the following code:
pecl install xdebug
Now you need to configure XDebug. As a default configuration you should put the following into /etc/php5/conf.d/xdebug.ini:
1 2 3
xdebug.profiler_enable_trigger = 1 xdebug.profiler_enable=0 xdebug.profiler_output_dir = /tmp
The first line enables the profiler by using a trigger. The trigger is a GET/POST parameter called XDEBUG_PROFILE=1 you can use whenever you start a local page via your webbrowser.
The second line enables the profiler by default and would create a profiler output file without a trigger parameter. We don’t want to do that all the time, so the value here is 0. If you want to enable your profiler the whole time, just put a 1 in there.
The third parameter is the path of the directory you want to write your profiler output files to. I’ve inserted /tmp as a default here, but you can change it to any other directory your webserver has write access to.
So an example URL to access a local webpage and create a profile output would be something like this:
There should be a cachegrind file in your output dir, e.g. cachegrind.out.12345
The number at the end of the filename is the apache pid. The name of the cachegrind file can be configured using another parameter, xdebug.profiler_output_name. A complete documentation of all possibilities can be found here.
Displaying the profile data
There are several tools to analyze the data created by the XDebug profiler. One of these tools is KCachegrind. KCachegrind visualizes traces generated by profiling, including a tree map and a call graph visualization of the calls happening.
As an example: you can analyze how often certain heavy-load methods are called within your application; that way you can find ways to minimize those calls, reduce them to a pure minimum and increase the performance of the application or website.