It is frustrating when your PHP application is really slow and you do not know which part of your code is taking up too much time.
Google considers 2 seconds as the optimal loading time for a fast loading website.
Enabling PHP XDebug Profiler
PHP’s Xdebug extension can be used to profile your web requests and CLI requests and understand why they are slow and which method is causing the bottleneck.
Follow this link to install XDebug on the server on which your PHP application is running: https://xdebug.org/docs/install
Once XDebug is installed successfully, open the xdebug configuration file and add the following line:
xdebug.profiler_enable = 1
Once you add the above line, the configuration file should look like this:
vagrant@dev:/etc/php/7.2/cli/conf.d$ cat 20-xdebug.ini zend_extension=xdebug.so xdebug.show_error_trace = 1 xdebug.profiler_enable = 1
The above file only enables the profile for CLI requests. For enabling the profile for web requests, add the same line into the following file:
vagrant@dev:/etc/php/7.2/fpm/conf.d$ cat 20-xdebug.ini zend_extension=xdebug.so xdebug.show_error_trace = 1 xdebug.profiler_enable = 1
Once the files are saved, restart the PHP FPM service:
service php7.2-fpm restart
Now you can open your phpinfo file and verify if the profiler is now enabled:
Generating the profile file
You can now open the slow webpage and PHP XDebug will create a profiler in the
profiler_output_dir mentioned above (i.e. ./tmp) which can also be customized in the xdebug ini file.
I opened the homepage of my PHP application and found these files in my
root@dev:/tmp# ls cache* -gGltrh -rw-r--r-- 1 1.6K Sep 23 10:29 cachegrind.out.3315.01c00e -rw-r--r-- 1 1.2M Sep 23 10:29 cachegrind.out.3315 -rw-r--r-- 1 2.1M Sep 23 10:31 cachegrind.out.3312 -rw-r--r-- 1 1.8K Sep 23 10:31 cachegrind.out.3312.0df7d7 -rw-r--r-- 1 1.2M Sep 23 10:31 cachegrind.out.3315.05bc8d -rw-r--r-- 1 1.2M Sep 23 10:31 cachegrind.out.3312.073921 -rw-r--r-- 1 2.0K Sep 23 10:31 cachegrind.out.3312.03dc36
Analyzing the generated files
Once these files are generated, you can open them in IntelliJ or PHPStorm for analysis:
Once you have finished the analysis, make sure to remove or comment the line
xdebug.profiler_enable in both your ini files and restart your FPM service. Otherwise the
tmp directory will get filled very quickly.
Other Free Tools
Apart from paid tools such as IntelliJ/PHPStorm, there are some free tools to analyze the generated