Profile Php Code

Your PHP application or website may run smoothly, or you may notice that it takes some time to load. In either case, it is a good practice to perform performance profiling. This technique allows you to understand how much time each function in your code takes and how many times they have been called. By doing so, you may discover interesting insights and improve the experience of your users and your web server.

The following tutorial assumes that you have PHP installed and know how to configure it.

What is Profiling

Profiling refers to the collection of real-time data about the execution of your application. In this article, we will focus on performance profiling of PHP code. This involves collecting data on the time consumption and call graph of invoked PHP functions.

performance profiling callers

Once the data has been collected, we can visualize and inspect it, looking into so-called “hot paths.” This will help us identify the parts of the program that consume the most time. Paying attention to the call counts can also provide useful insights. For example, if a small function is called a hundred thousand times per request, it might be worth considering caching, optimizing that function, or even redesigning the entire algorithm.

Prepare Xdebug

To efficiently collect profiling data, you need to use a PHP extension called Xdebug. If you are already debugging your code or performing other profiling activities, you should already have it installed. If not, you can follow the link provided and install the extension for your platform.

  • Follow the steps on xdebug.org/docs/install.
  • Verify that you have the Xdebug extension by running php -v or checking phpinfo().
  • Optionally, ensure that you have the zlib PHP extension enabled, as this will make your profile files significantly smaller.
See also  Introducing ProgramMatek: A Comprehensive Guide to PHP Accounting Software

Next, you need to make sure that the xdebug.output_dir directive is set to a writable directory. Additionally, ensure that you have at least 1GB of free space in that directory. Make sure the directory exists and is writable.

Launch Built-In Server with Profiling

Now it’s time to start profiling. At this point, you should have the following:

  • Visual Studio Code
  • PHP Tools for Visual Studio Code
  • PHP with Xdebug (as described above)

Open Folder

Launch Visual Studio Code and open your PHP project by selecting “Open Folder” and choosing the appropriate directory. You will see something like the following:

VSCode Explorer

launch.json

Either open or create a .vscode/launch.json file, and add the following configuration to enable launching the built-in server with profiling:

.vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Built-in server & Profile",
      "type": "php",
      "request": "launch",
      "runtimeArgs": ["-S", "localhost:8888", "-t", "public"],
      "profile": true
    }
  ]
}

In the above configuration, the development PHP server will run on port 8888 with the web root located at ./public. You can change these values to suit your needs. The profile setting being set to true instructs the debugger to configure additional Xdebug settings for profiling.

After making this change, you should see the following drop-down menu in the “Run and Debug” view:

Run and Debug with Profiling launch setting

Collect Profiling Data

Now, run the project using the newly created launch setting. You can do this by pressing F5 or clicking the “Start Debugging” command. In the “Debug Console” panel, you will see the following output:

debug output built-in PHP server

Open your web browser and visit the URL you want to profile. For example, in our case, it would be http://localhost:8888/ or any other page in your application. Keep in mind that if you make multiple requests, the profiling file may become larger and take more time to load and process.

See also  Aav Php Eb

After you have opened the application in your web browser, stop the debugging session in VS Code (press Shift+F5) and get ready to inspect the profile file. The file will be stored in the path specified by your xdebug.output_dir setting and will be named cachegrind.out.{process id}.gz.

Inspecting Profile File

Now that you have collected the profiling data, it’s time to dig into the details. The profile file, cachegrind.out...gz (or without .gz if you don’t have the zlib PHP extension enabled), contains every single function call made during the request. The file size can range from a few kB to hundreds of MB.

You can open the profile file by either dragging and dropping it directly into the VS Code window or using the “Open Profile File (Xdebug Profiling Output)” command.

Call Time View

The profile view opens on the first tab, which is the “Call Time” view. Here, you can find all the called functions aggregated and sorted by the time consumed. The view can be filtered by name and sorted by clicking on the table header. You can also choose to list only functions, files, or internal PHP functions.

profiling call time

This view gives you a good understanding of which functions are the most time-consuming in your code. Personally, I find it helpful to check the “Calls” column, which provides information about functions that are called excessively.

Hover your mouse over a row to see the full function name as collected by Xdebug. This information includes details such as whether the function was called by an instance or statically and the full namespaced name of the class or function.

Double-click on a row to jump directly to the file.

See also  Send Emails to Multiple Recipients in PHP

Click the “Navigate” button to open the next view, which is the “Function Details” view.

Function Details

The “Function Details” view allows you to browse through the call graph. Each bubble represents a function, showing the time it consumed (including the called functions) and the call direction.

function details

Clicking on the bubbles allows you to navigate through the call graph.

Hot Path

The last view is an extension of the text editor itself. It highlights the source code lines that take a considerable percentage of the overall application time.

PHP profile hot path

This feature visualizes the “hot paths” in your source code, using various shades of red to indicate the amount of time. On the right side, you can see the percentage of overall time and the time in milliseconds. The percentage can be configured through the “phpprofiler.hotpath.threshold” setting (default is 1%).

Profile Console Program

There is a shortcut for quickly profiling a .php file as a console program. If you already have a .vscode/launch.json file, you can specify the "profile": true setting, just like we did with the built-in web server:

launch.json

{
  "name": "Profile current script",
  "type": "php",
  "request": "launch",
  "program": "${file}",
  "cwd": "${fileDirname}",
  "profile": true,
  "externalConsole": false
}

If you don’t have a launch.json file, you can simply press F5 and choose “Profile current Script.” The script file will be launched with profiling, and when finished, the profiling result will open automatically.

profile console PHP program

The script above calculates the Fibonacci sequence and profiles its performance.

Conclusion

Although this tutorial may seem longer than necessary, we hope that our tools make PHP profiling simple and easy to understand. It is always recommended to profile your application before deploying it to production. By doing so, you can save yourself, your server, and your users valuable time.

See also