PHP Profiling Tools

Profiling tools are essential for PHP code optimization. Profiling is the process of inspecting a program’s behavior with respect to time and memory usage, so you can find out which areas will benefit from optimization.

This article goes through some of the most popular profiling tools, including XHProf, Xdebug, Clockwork.

Clockwork

Clockwork is a browser extension, providing tools for debugging and profiling your PHP applications, including request data, application log, database queries, routes, visualisation of application runtime and more.

Clockwork uses a server-side component, that gathers all the data and easily integrates with any PHP project, including out-of-the-box support for major frameworks.

Read more and try it out on the Clockwork website.

This repository contains the server-side component of Clockwork.

Installation

This readme contains installation and usage instructions for the Laravel framework, for other integrations check out the Clockwork website.

Install the Clockwork library via Composer.

$ composer require itsgoingd/clockwork

If you are running the latest Laravel version, congratulations you are done!

For Laravel versions older than 5.5, you’ll need to register the service provider, in your config/app.php:

'providers' => [
	...
	Clockwork\Support\Laravel\ClockworkServiceProvider::class
]

By default, Clockwork will only be available in debug mode, you can change this and other settings in the configuration file. Use the vendor:publish Artisan command to publish the configuration file into your config directory.

Clockwork comes with a clock() helper function, which provides an easy way to add records to the Clockwork log and events to the timeline.

If you prefer to use a Facade, add following to your config/app.php:

'aliases' => [
	...
	'Clockwork' => Clockwork\Support\Laravel\Facade::class,
]

Note: If you are using Laravel route cache, you will need to refresh it using the route:cache Artisan command.

Usage

To interact with the data collected by Clockwork, you will need to

Clockwork comes with a clock() helper function, which provides an easy way to add records to the Clockwork log or events to the timeline.

You can also access Clockwork using the Clockwork facade, resolving from the container app('clockwork') or typehinting Clockwork\Clockwork.

Logging

All data logged using the Laravel log methods will also appear in the Clockwork log tab for the request.

You can also use the Clockwork log directly, with the benefit of rich logging capabilities. You can safely log any variable, from a simple string to an object.

Logging data to Clockwork can be done using the helper function, which even supports logging multiple values at once

clock(User::first(), auth()->user(), $username)

If you want to specify a log level, you can use the long-form call

clock()->info("User {$username} logged in!")

Timeline

Clockwork adds some general application runtime timeline events for you by default.

To add a custom event to the timeline, you’ll need to start an event with an unique name and description first.

clock()->startEvent('twitter-api-call', "Loading users latest tweets via Twitter API")

After executing the tracked block of code, you can end the event, using it’s unique name.

clock()->endEvent('twitter-api-call')

Events that are not stopped explicitly will simply finish when the application runtime ends.

Configuration

By default, Clockwork will only be available in debug mode, you can change this and more settings in the configuration file.

You can publish the configuration file using the vendor:publish artisan command to

  • set when Clockwork should be enabled
  • enable or disable the web UI
  • configure how the request metadata is stored
  • set what data should be collected
  • how long Clockwork stores log files

PHP Debug Bar

This is a package to integrate PHP Debug Bar with Laravel. It includes a ServiceProvider to register the debugbar and attach it to the output. You can publish assets and configure it through Laravel. It bootstraps some Collectors to work with Laravel and implements a couple custom DataCollectors, specific for Laravel. It is configured to display Redirects and (jQuery) Ajax Requests. (Shown in a dropdown) Read the documentation for more configuration options.

Debugbar 3.3 Screenshot

Note: Use the DebugBar only in development. It can slow the application down (because it has to gather data). So when experiencing slowness, try disabling some of the collectors.

This package includes some custom collectors:

  • QueryCollector: Show all queries, including binding + timing
  • RouteCollector: Show information about the current Route.
  • ViewCollector: Show the currently loaded views. (Optionally: display the shared data)
  • EventsCollector: Show all events
  • LaravelCollector: Show the Laravel version and Environment. (disabled by default)
  • SymfonyRequestCollector: replaces the RequestCollector with more information about the request/response
  • LogsCollector: Show the latest log entries from the storage logs. (disabled by default)
  • FilesCollector: Show the files that are included/required by PHP. (disabled by default)
  • ConfigCollector: Display the values from the config files. (disabled by default)
  • CacheCollector: Display all cache events. (disabled by default)

Bootstraps the following collectors for Laravel:

  • LogCollector: Show all Log messages
  • SwiftMailCollector and SwiftLogCollector for Mail

And the default collectors:

  • PhpInfoCollector
  • MessagesCollector
  • TimeDataCollector (With Booting and Application timing)
  • MemoryCollector
  • ExceptionsCollector

It also provides a Facade interface for easy logging Messages, Exceptions and Time

Installation

Require this package with composer. It is recommended to only require the package for development.

composer require barryvdh/laravel-debugbar --dev

Laravel uses Package Auto-Discovery, so doesn’t require you to manually add the ServiceProvider.

The Debugbar will be enabled when APP_DEBUG is true.

If you use a catch-all/fallback route, make sure you load the Debugbar ServiceProvider before your own App ServiceProviders.

Laravel without auto-discovery:

If you don’t use auto-discovery, add the ServiceProvider to the providers array in config/app.php

Barryvdh\Debugbar\ServiceProvider::class,

If you want to use the facade to log messages, add this to your facades in app.php:

'Debugbar' => Barryvdh\Debugbar\Facade::class,

PHP Profiler Tool

The PHP Profiler tool enables the collection and display of execution profile data on PHP software source code bases of arbitrary size. It is a member of SD’s family of Profiler tools.

PHP Profiler Features

  • Provides execution counts on basic blocks, or timing profiles on methods
  • PHP4 and PHP5 versions
  • No special configuration of PHP server required, nor XDebug (works with HipHop!)
  • Works with arbitrary subsets of source code base
  • Can accumulate data from multiple test runs
  • Handles tens of thousands of files
  • Extremely low probe overhead
  • Produces profile report by file and directory. The same report is available as XML to enable custom report generation.
  • The probe installer component runs on Windows
  • Profile data display can run on any platform with a full JVM

The PHP Profiler tool has an intuitively simple display. It shows

  • Available Profile Data (PFD) result files
  • Selected/accumulated/computed PFD files
  • List of files for which profile data is being collected
  • Locations of probe points in files
  • Browsable source text of file of current interest
  • Execution counts and relative execution frequency of each probe point on file source text
  • Color- and size- coded (hot is red and wide, cold is blue) overlay of frequency data on source code
  • Summary statistics for subsystems

Xdebug

Xdebug

Xdebug is easy to install and operate, and it does not require code changes. This powerful PHP profiler was released in 2002. Since then, it has an unprecedented growth and remains popular among PHP developers. Its major features include stack and function tracing, code coverage analysis, remote debugging, and scripts profiling. As this article suggests, we will focus on its profiling feature. It provides the developer the detailed information about the script performance, helps identify which parts of the code are slow. Then, collected information is being stored in cachegrind compatible file and can be analyzed using one of the external tools, such as KCachegrind, WinCacheGrind, xdebugtoolkit, or the web-based analyzer Webgrind as shown below.

Xhprof

Xhprof was created by Facebook and includes a basic UI for reviewing PHP profiler data. It aims to have a minimum impact on execution times and require relatively little space to store a trace. Thus, you can run it live without a noticeable impact on users and without exhausting the memory. For full functionality, Paul Reinheimer has created Xhgui, an enhanced UI project for reviewing, comparing and analyzing profile data as shown below.

Pros

  • A standard method and level performance PHP profiler can help you track down memory leaks and performance issues that are leading to high memory usage. If memory usage is a problem, standard profilers are the solution.
  • Identify the causes of high CPU usage and optimize app performance to work within a normal CPU level. Standard profilers are perfect for this type of performance tuning.

Cons

  • Application snapshots are only taken periodically and might not capture the full picture of the problem. A standard PHP profiler doesn’t run continuously.
  • Standard profilers are resource-intensive and slow developers down. They are not lightweight, which means they need a full-stop on development before running.
  • As mentioned above, some standard profilers like Xdebug require the use of other tools to analyze the profiler data. This also slows down the time-to-insight for developers.

Tracing profilers

Tracing profilers are lighter weight than standard profilers and can be used while you code. Unlike standard profilers, you can use tracing profilers everyday, and it won’t slow you down. These are designed to catch errors in real time while you’re developing, instead of catching errors after the fact. You can think of tracing profilers as your first line of defense in your war on bugs.

There are two robust PHP profilers that belong to the tracing type: Z-Ray and Prefix.

Z-Ray

To win the war on bugs, Z-Ray is another tool to look into that is very significant in the PHP developer’s toolkit. It has PHP debug capabilities that are unlike anything you’ve ever seen before. It displays all the internal details of a page request, across all the PHP scripts involved in building the page. It is injected into the response coming from your PHP app. Also, it is shown right in the browser that you are using for development. The good thing is that you get vastly greater insight without changing your development workflow.

Prefix

Prefix from Stackify is a free lightweight PHP profiler for developers. It caters .NET and Java with PHP coming soon. It allows getting some detail from your server-based profiling. It runs on the desktop and gives details about what their code is doing while creating or testing their apps. It is the world’s best log viewer for developers. For example, with each ASP.NET web request, you can see all your log statements plus many other details.

Pros

  • Tracing profilers can be used every day to catch errors while they happen. They allow developers to debug in any environment, even production.
  • Allows developers to trace PHP executing, function calls, and information requests during run-time.
  • Because they’re used while coding, tracing profilers help you identify errors quickly and easily. No need to stop development.
  • Many tracing profilers are completely free to use.

Cons

  • Tracing profilers offer limited insights, like identifying heavy-load problems and bugs. Prefix, for example, only monitors web request issues.
  • They cannot identify CPU or memory usage issues.
  • They do not provide full-stack performance monitoring like APMs.

Conclusion

Xhprof is a highly efficient, fully featured PHP 5.4+ profiler that understands your code and can help you find performance bottlenecks in seconds. One of the ways it does this is by recording application traces and then formatting them into an easily readable reports. This feature makes it much easier to locate large number of slow code lines and hence save you valuable debugging time.

Leave a Comment