Profiling Your Script
Open the guilty page in your browser, appending ?XDEBUG_PROFILE=password to the URL. The profiler is disabled by default, but adding this URL parameter will switch it on.
After the PHP has executed and the page loaded there will be one or more cachegrind.out.* files in your /tmp folder. If you are profiling on a remote server, download these to your local machine and delete them from the server.
Analyzing The Data
The cachegrind.out files contain detailed information on which functions were called, how many times, and how long each call took. You won’t get much simply by reading these files. You need a tool such as KCachegrind or Profiling Viewer to analyze the raw data and present it in a useful way. If you’re on a Mac, it’s well worth the $35 for Profiling Viewer to save time and avoid the stress of compiling KCachegrind.
Open the cachegrind.out file using KCachegrind or Profiling Viewer. Both tools display a list of all the functions called and the percentage of the overall execution time spend in each. The “main” function is selected by default.
You will also be able see a visual representations of this data in the form of a Map or Call Graph. I find a call graph of the main function the most useful, as it clearly shows the execution flow and the percentage of time spent at each step. Take some time to explore the tool.
So Now What?
Once you have identified the functions slowing your script down, how you address that slow down depends on your application. Can the function be rewritten in a more efficient way? Is it performing any unnecessary tasks? Does the function call need to be synchronous?
In my case, several API calls to an external service were the culprit. One call was completely unnecessary and could be dropped. There others I moved to a queue to be executed at a later time from a cron job. The result was a dramatic decrease in the execution time of the order process.