Profiling PHP Using xdebug & kcachegrind
See the blogpost on xdebug installation before continuing.
You need to add following line to /etc/php5/apache2/php.ini to enable profiling of php scripts.
Now restart the apache server by issuing following command.
sudo apache2ctl restart
When ever you access a php page through apache, xdebug will create a file something like cachegrind.out.15093. xdebug by default uses /tmp directory to dump files which contain profiling information. You can change this target directory by using xdebug option xdebug.profiler_output_dir and you can change result file name by using the option xdebug.profiler_output_name.
See more xdebug profiling options.
Some times you don't want to profile all requests. xdebug provides a selective mechanism to trigger profiling of specific requests. In order to enable this option you have to add following configuration option to php.ini.
Now you can trigger profiling of specific requests by adding XDEBUG_PROFILE to the query part of the GET request.
Analyzing Profiling results
We need to use kcachegrind to analyse profile file results. We can install kcachegrind by issuing following command.
sudo apt-get -y install kcachegrind
Now open your profle result file in kcachegrind and you can visuall inspect which part of your script is eating cpu resources. Callmap & Callgrap provide easy to understand visualizations to find bottlenecks in your script.