PHP Advent

#[Tooling]

PHP Profiling: Xdebug, SPX, XHProf, and Blackfire Compared

· 17 min read

A glowing execution flamegraph and call graph displayed across dual monitors in a dark engineering workspace.

When a PHP request runs slowly, a profiler shows where it spends its time. Manual timestamps and log statements leave you to piece that picture together yourself. A function profiler records calls and their costs; the available timing and memory metrics depend on the tool and its configuration.

Application Performance Monitoring (APM) tools alert you when an HTTP endpoint exceeds its latency budget, but lack the function-level detail needed to locate the exact line causing the delay. A profiler separates time spent waiting on external I/O from time spent doing CPU work. That tells you whether PHP is waiting on a database socket or working through nested serialization loops.

For modern PHP applications, Xdebug gives you local call trees, while SPX includes a web UI. XHProf and its forks let you host the function data yourself; Blackfire provides hosted analysis. Each tool has a different balance of overhead and diagnostic detail. Before deploying an extension, check its release against your exact PHP minor version.

Understanding Profiling Metrics

Before sorting a profiler report, decide which metric answers your question. A function can look expensive in one column and contribute little to the request duration you are trying to reduce.

Wall Time Versus CPU Time

Wall time is the elapsed time between a function starting and returning. CPU time counts only the time the operating system allocated to the PHP process on a CPU core to execute instructions inside that function.

High wall time with low CPU time means the PHP process spent most of its time waiting for something external. Slow database queries, disk reads, Redis locks, and third-party HTTP APIs are common causes. Refactoring a PHP algorithm will not speed up these endpoints when the delay comes from the network or storage system. When you do change the code, static analysis can check for correctness errors alongside the performance test.

A function with high wall time and similar CPU time may be compute-bound. Check system and request metrics to confirm it before changing an algorithm or adding a cache.

Inclusive Time Versus Exclusive Time

Every profiler records inclusive and exclusive time for each function. You will also see exclusive time labeled self-time.

Inclusive time includes the time spent in a function and all the child functions it calls. An entry point such as index.php or a framework kernel handler almost always accounts for 100 percent of inclusive wall time. Sorting by inclusive time shows the call stack from the root controller down to the leaf functions.

Exclusive time counts only the code in the function itself, leaving out time spent in child functions. Sort by this column to isolate the hot path. If a utility method accounts for 45 percent of total exclusive time, the CPU spent nearly half the request in that method, wherever it appears in the call tree.

Memory Allocation Metrics

Memory metrics show how much RAM the Zend Engine requested from the system allocator during a request. Profilers record both the change in memory usage and the peak usage.

Memory delta is the net change in memory consumption across a function call. A function might allocate ten megabytes to build an in-memory report, then free that data before returning. Its memory delta would be negligible despite the temporary pressure on the engine. Peak memory records the highest allocation reached during the call. Finding functions with high peaks helps prevent out-of-memory fatal errors and reduce fragmentation in long-running CLI workers.

Worked Example: Diagnosing a Slow Batch Function

To understand how profiler output identifies performance bottlenecks, consider an unoptimized batch processing function. In this scenario, an application processes an array of order items, verifying customer authentication tokens and calculating regional sales tax.

<?php

declare(strict_types=1);

namespace App\Billing;

class OrderProcessor
{
    /**
     * @param array<int, array{id: int, user_token: string, amount: int}> $orders
     * @return array<int, array{id: int, tax: float, valid: bool}>
     */
    public function processBatch(array $orders): array
    {
        $results = [];

        foreach ($orders as $order) {
            $isValid = $this->verifySecurityToken($order['user_token']);
            $tax = $this->calculateTax($order['amount']);

            $results[] = [
                'id' => $order['id'],
                'tax' => $tax,
                'valid' => $isValid,
            ];
        }

        return $results;
    }

    private function verifySecurityToken(string $token): bool
    {
        // Expensive cryptographic hash evaluated on every single iteration
        $hash = hash_pbkdf2('sha256', $token, 'salt_value', 10000, 32);

        return str_starts_with($hash, 'a');
    }

    private function calculateTax(int $amount): float
    {
        return round($amount * 0.0825, 2);
    }
}

Run this code with a representative batch containing repeated tokens, then inspect the call counts. Application logs can tell you that processBatch() ran, but a profile shows where its time went. This token check is a stand-in for repeated expensive work, not an authentication design to copy into an application.

Reading the Profile Output

Opening the generated profile in a viewer surfaces the execution hierarchy:

  • OrderProcessor::processBatch() should have high inclusive time because it contains the whole operation. Compare that with its self-time to see how much work happens in the loop body itself.
  • Expanding the callees of processBatch() reveals two downstream calls: calculateTax() and verifySecurityToken().
  • OrderProcessor::calculateTax() is called once per order. Check whether its aggregate time is material before changing the arithmetic.
  • verifySecurityToken() is also called once per order. Compare its aggregate time and call count with the other functions. The repeated hash_pbkdf2() calls are the likely hot path in this example.

The profile should reveal repeated key derivation for duplicate tokens. Confirm that finding with the actual call counts and timings from your own run before optimizing.

Resolving the Bottleneck

With the hot path clearly visible, we optimize the function by memoizing the verification results within the batch lifecycle:

<?php

declare(strict_types=1);

namespace App\Billing;

class OrderProcessor
{
    /** @var array<string, bool> */
    private array $tokenCache = [];

    public function processBatch(array $orders): array
    {
        $results = [];

        foreach ($orders as $order) {
            $token = $order['user_token'];
            $isValid = $this->tokenCache[$token] ??= $this->verifySecurityToken($token);
            $tax = $this->calculateTax($order['amount']);

            $results[] = [
                'id' => $order['id'],
                'tax' => $tax,
                'valid' => $isValid,
            ];
        }

        return $results;
    }

    private function verifySecurityToken(string $token): bool
    {
        $hash = hash_pbkdf2('sha256', $token, 'salt_value', 10000, 32);

        return str_starts_with($hash, 'a');
    }

    private function calculateTax(int $amount): float
    {
        return round($amount * 0.0825, 2);
    }
}

Run the same input again. verifySecurityToken() should now be called once per distinct token held by this OrderProcessor instance. Compare total wall time and the hash call count in both profiles. In a real authentication flow, cache only results whose validity and lifetime permit it; an instance reused across requests would need an explicit reset.

A split widescreen monitor displaying a before-and-after performance benchmark with high and low latency indicator bars.

Xdebug Profiler: Exhaustive Local Inspection

Xdebug is a maintained diagnostic extension for PHP development. Its profiler generates Cachegrind-compatible files. Check the Xdebug support page for the extension release that matches your PHP version before installing it.

Installation and INI Settings

Install the extension using PECL or your operating system package manager:

pecl install xdebug

Enable the profiler in your php.ini configuration. Set xdebug.mode to profile and use trigger mode to prevent the profiler from running on every unprompted asset or health check request:

zend_extension=xdebug.so

[xdebug]
xdebug.mode=profile
xdebug.start_with_request=trigger
xdebug.output_dir="/tmp/xdebug"
xdebug.profiler_output_name="cachegrind.out.%p.%t"

In trigger mode, Xdebug profiles a request only when an authorized parameter is present. Append ?XDEBUG_PROFILE=1 or ?XDEBUG_TRIGGER=1 to the URL, pass an XDEBUG_PROFILE cookie, or toggle an Xdebug browser extension. For a CLI script, use XDEBUG_TRIGGER=1 php script.php.

Consult the official Xdebug profiler documentation for full details on output naming templates and triggering options.

What the Output Shows

Xdebug writes binary or text files in the Valgrind Callgrind format, typically at /tmp/xdebug/cachegrind.out.%p.%t. These files are difficult to read in a text editor, so use a viewer:

  • KCachegrind on Linux desktop environments.
  • QCachegrind on macOS and Windows, available via package managers such as Homebrew.
  • Webgrind, a PHP-based web interface that reads Cachegrind files directly from the output directory and renders call trees in the browser.

Cachegrind viewers let you explore an interactive call graph and caller-callee trees, then sort by inclusive or exclusive cost. Their visual call maps also show cycles and recursive execution loops.

Overhead and Production Suitability

Active profiling adds work to function calls and writes a potentially large output file. Its overhead varies with the application and the selected Xdebug modes, so measure it in your own workload rather than applying a universal percentage.

Use Xdebug profiling primarily on a local or isolated staging replica. Triggered profiling can be used for a controlled production investigation only after restricting who can trigger it, limiting disk use, and accepting its measurement overhead. Do not enable profiling for every production request.

SPX: Fast Local Profiling with Built-in Web UI

SPX is a fast PHP profiling extension written in C, created and maintained by NoiseByNorthwest. It supports PHP 8.0 through modern PHP 8 releases. Its interactive web interface ships inside the extension, so you can inspect profiles without installing a separate viewer.

Installation and INI Settings

SPX supports PHP 5.4 through 8.5 according to its current repository requirements. Install its PHP development package and zlib development headers first, then build the latest release branch with the standard PHP extension toolchain:

# Clone the repository
git clone https://github.com/NoiseByNorthwest/php-spx.git
cd php-spx
git checkout release/latest

# Prepare, compile, and install the extension
phpize
./configure
make
sudo make install

After compilation, enable the extension and configure its web access credentials in your php.ini or a dedicated spx.ini configuration file:

extension=spx.so

[spx]
spx.http_enabled=1
spx.http_key="profiler_dev_secret"
spx.http_ip_whitelist="127.0.0.1,::1"
spx.data_dir="/tmp/spx"

Check the NoiseByNorthwest php-spx repository for updates on release tags and compilation prerequisites across specific Linux distributions.

Accessing the Web UI and Reading Output

SPX does not need external software or a desktop viewer. Open its interface by submitting an HTTP request with the configured authentication parameters:

https://my-app.test/?SPX_KEY=profiler_dev_secret&SPX_UI_URI=/

This URL opens the control panel. Enable profiling there, refresh the request you want to examine, then select its new report. The interface provides three main views:

  1. The interactive flamegraph shows the call stack over time. Wide blocks identify functions taking a disproportionate share of execution time.
  2. The flat profile lists every executed function in a sortable table. You can sort by exclusive or inclusive wall time, CPU time, and allocated memory.
  3. The execution timeline traces millions of function calls in order on a horizontal timeline. It shows when database queries or external API calls paused execution.

SPX also supports profiling command-line scripts by prefixing the command with environment variables: SPX_ENABLED=1 SPX_REPORT=full php console.php app:import.

A close-up view of an ultrawide monitor displaying an interactive hierarchical execution flamegraph across a dark theme interface.

Overhead and Production Suitability

SPX offers selectable metrics and a sampling mode. Its documentation explains how timing small functions can be distorted by profiler overhead. Measure overhead against the same request without active profiling; the result depends on the workload, report mode, and selected metrics.

SPX is not intended for public production environments. Its HTTP controls rely on query parameters and IP whitelisting; a misconfigured public server could expose internal function names, source paths, database table structures, and memory profiles to attackers. Use it for local development, staging, or internal tests where you want to view flamegraphs without setting up external tools.

XHProf and Maintained Forks: The Self-Hosted Standard

Facebook developed XHProf in 2009 to profile live production web requests. It was designed as a lightweight function-level profiler that captures caller-callee pairs with little performance overhead.

In December 2010, Paul Reinheimer described the original community workflow in his PHP Advent article on profiling with XHGui. Developers used automatic prepend files and MongoDB storage to collect production traces without heavyweight debuggers.

Current Maintenance Status in Modern PHP

Facebook abandoned the original XHProf repository when it moved its internal infrastructure to HHVM. For modern PHP 8.x environments, community forks provide updated versions:

  • longxinH/xhprof: This maintained fork has a PECL release and states support for PHP 7/PHP 8. The PECL xhprof package lists longxinH/xhprof on GitHub as its source. PECL's minimum version declaration does not guarantee that the last release builds on every newer PHP minor release. Check compatibility before relying on PHP 8.5.
  • tideways/php-xhprof-extension: Tideways developed this widely used fork for PHP 7 and early PHP 8, then officially archived it. Its recommendations now point users to the mainstream PECL XHProf package or the commercial Tideways platform.

Installation and Usage

To install the current maintained XHProf extension on PHP 8:

pecl install xhprof

Enable the extension in your php.ini:

extension=xhprof.so
xhprof.output_dir="/tmp/xhprof"

Xdebug and SPX can run entirely through INI triggers. XHProf is commonly started from your application bootstrap or an auto_prepend_file script:

<?php

// Start profiling with CPU and memory tracking
xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);

// Execute your application request
$app = new App\Kernel();
$app->handleRequest();

// Stop profiling and retrieve the raw trace data
$profilerData = xhprof_disable();

// $profilerData contains an array of caller-callee metrics
// Example key: "App\Kernel::handleRequest==>App\Billing\OrderProcessor::processBatch"

Visualizing Output with XHGui

xhprof_disable() returns an associative array of parent-child function transitions, with call counts, wall time, CPU time, and memory usage. XHGui turns that raw data into dashboards.

XHGui is a separate viewer and collection application. Its storage and installation options depend on the version you choose. A deployed viewer can surface:

  • Request profile history.
  • Function call counts and costs.
  • Comparisons of selected runs.
  • Call graphs, when the viewer is configured to generate them.
An illuminated directed acyclic graph network visualization displaying function caller-callee execution trees on a curved widescreen monitor.

Overhead and Production Suitability

XHProf records function calls and can be enabled for a selected subset of requests. Its overhead depends on call frequency and enabled metrics. Benchmark that overhead on your workload before using it in production.

In a production configuration, an auto_prepend_file can choose a small random subset of requests and call xhprof_enable() only for those requests. Add an authorized storage path and a shutdown handler that saves the result of xhprof_disable(); the code above merely returns an array. Restrict access to reports because paths and function names can expose internals.

Hosted Profiling: Blackfire in Production

Hosting your own profiling infrastructure means maintaining MongoDB clusters, ingestion workers, and web interfaces. Commercial hosted profilers handle that work and provide production safety controls.

Blackfire Architecture and Triggered Profiles

Blackfire, operated by Upsun, splits the profiling workflow across a PHP probe extension installed on the web server and a background agent.

Blackfire's on-demand profiles are triggered for selected requests. Its monitoring and continuous profiling features have separate configurations, so check which modes are enabled on the host. Do not assume the installed probe has literally zero overhead.

An authorized developer starts an on-demand profile through the Blackfire CLI, a browser extension, or an automated test suite. The request carries a cryptographically signed HTTP header (X-Blackfire-Query). The probe checks the signature against the server credentials, instruments that request, and sends the captured callgraph to the local agent daemon through a Unix socket.

Blackfire Installation and Configuration

Follow the official Blackfire installation documentation to install the CLI, register your environment credentials, and install the agent and PHP probe. On a Debian-based host with Blackfire's package repository configured, the sequence is:

# Install the agent daemon after adding Blackfire's package repository
sudo apt install blackfire-agent

# Register the agent using the credentials from your Blackfire environment
sudo blackfire agent:config
sudo systemctl restart blackfire-agent
sudo blackfire php:install

Configure the probe in your php.ini:

extension=blackfire.so

[blackfire]
blackfire.agent_socket="unix:///var/run/blackfire/agent.sock"
blackfire.log_level=1

To profile an endpoint, run the Blackfire command-line client:

blackfire curl https://my-app.example.com/api/orders

The CLI returns a dashboard link where you can inspect call costs and compare profiles. Repeat runs to check for noise: a single invocation is not a statistically averaged benchmark. Blackfire also offers continuous profiling with a separate setup.

An operations console displaying a live production performance breakdown with glowing radial metrics and hierarchical transaction maps.

Production Suitability

Blackfire offers production workflows. Configure its credentials and access controls according to its documentation, and decide whether sending captured profiling data to a hosted dashboard fits your data policy.

Profiler Comparison and Selection

Selecting the right profiler depends on your deployment target, your hosting constraints, and the specific question you need to answer.

Local Development and Debugging

Xdebug works well on a developer laptop when you need to diagnose complex logic errors, inspect variable values, or trace deeply nested object creation. Its PhpStorm and VS Code integrations let you step through code line by line. Its Cachegrind output records every function call.

When you want a browser UI without a separate Cachegrind viewer, SPX is a useful local choice. Its flamegraph and flat view can help you compare changes to an algorithm.

Staging and Pre-Production Validation

Use staging profiles to catch regressions before deployment. Run a representative request under the same PHP, OPcache, and database conditions as production, then compare call counts and the critical path with the earlier profile. Blackfire can also evaluate performance assertions in CI when you configure tests for your own application.

Live Production Diagnostics

For live production, prefer tools designed for controlled capture. Use Xdebug profiling only for a tightly scoped investigation with access and disk limits; keep SPX on isolated debugging instances behind a VPN or internal load balancer.

For production, Blackfire provides hosted analysis with access controls and on-demand capture. If profiling data must stay on premises, a compatible XHProf build with a protected internal viewer is an option, provided you validate its PHP version support and sample rate.

Step-by-Step Diagnostic Workflow

When an endpoint triggers a production latency alert, use the measurements to decide what to investigate:

  1. Check CPU utilization and disk I/O in your APM or server metrics. Low CPU usage with high request time points to an I/O-bound endpoint. A CPU core pinned at 100 percent points to a compute-bound endpoint.
  2. Capture the exact request payload and database state that triggered the slowdown. Reproduce the transaction in staging or a local container with SPX or Xdebug enabled.
  3. Trigger the profiler with a secure key or trigger parameter. Exclude static assets, favicon requests, and health checks from the run.
  4. Open the profile and sort functions by exclusive self-time. Start with the top three functions consuming the most internal clock cycles.
  5. Check call counts as well as durations. Small, fast functions can add up when nested loops call them thousands of times. Replacing an O(N^2) lookup with a hash map or memoizing repeated returns routinely produces large speedups.
  6. Check call counts and wall times for PDO statements, Redis commands, and cURL requests. Look for N+1 query loops that execute individual SQL queries inside a foreach loop instead of batching the lookup into a single query.
  7. When reporting a regression or optimization to your team, record the hardware specifications, baseline latency, reduction in call counts, and final profile comparisons. The practices for putting personal experience into technical writing help make those reports verifiable. If an AI tool drafts the summary, check an AI rewrite before you send it: rewrites can round or drop the numbers you measured.
  8. Profile the optimized code with the same input payload. Check that the targeted function's exclusive self-time has decreased and that total wall time meets your latency budget.

Common Profiling Mistakes to Avoid

A profile can mislead you when the test environment or profiler configuration differs from real operating conditions.

Leaving Profilers Enabled Globally

Setting xdebug.start_with_request = yes or enabling XHProf unconditionally profiles every request. Thousands of trace files can reach disk within minutes, exhausting inodes, saturating storage throughput, and inflating application latency. Use trigger modes or probabilistic sampling.

A rack of high-density blade servers in a data center with arrays of illuminated status indicators and fiber optic cabling.

Confusing Profiler Overhead with Application Latency

Instrumented profilers add overhead to each function call. When an application calls lightweight getters or string utilities very often, those hooks can distort the observed duration. Compare relative percentages and call counts; the absolute microsecond figures for small utilities are not exact production timings.

Profiling with Synthetic or Empty Databases

A function tested against a tiny local SQLite database may behave differently against a much larger remote production database. Use realistic data volumes and representative network latency. Otherwise, unindexed lookups, memory-intensive hydration, and N+1 query loops may not show up in the profile.

Neglecting OPcache and the JIT Compiler

Keep OPcache enabled during profiling. Production OPcache stores precompiled script bytecode in shared memory, removing file compilation overhead. With it disabled, file loading and class compilation consume a substantial part of the profile and obscure the runtime bottlenecks you would see in production.

Frequently Asked Questions

What is the difference between an APM and a profiler?

An Application Performance Monitor (APM) tracks HTTP response codes, aggregate transaction response times, and database query durations across your server fleet. A profiler records the exact function call stack, call counts, and memory allocations for a single request by hooking into the PHP runtime. Use APM to find the slow endpoint and a profiler to find the function responsible.

Can I safely run Xdebug in production if I use trigger mode?

Trigger mode reduces active profiling, but it does not replace access control. An unauthorized visitor who discovers a public trigger can start expensive profiling runs and consume disk space. Use Xdebug only on an isolated production instance when a specific investigation justifies it, and restrict the trigger and output directory.

What is the difference between instrumented profiling and sampling profiling?

Instrumented profiling records function entries and exits. It can show call counts and a detailed hierarchy, at the cost of overhead that may distort short calls. Sampling observes the stack at intervals and estimates where time is spent. It usually collects less detail and may miss short-lived calls between observations; its overhead also depends on the sampling rate and implementation.

Why does a profiled request take longer than an unprofiled request?

The PHP engine does extra work at every function boundary while a profiler is active. It reads high-resolution clocks, increments counters, measures memory, and updates the callgraph. That work increases request duration. Read the results in terms of relative call proportions, the hot-path hierarchy, and call counts rather than absolute latency.

Does the PHP JIT compiler affect profiling measurements?

Yes. PHP 8 introduced the Just-In-Time (JIT) compiler. Some instrumentation can alter how code is executed. If your production workload uses JIT, compare unprofiled runs with the same JIT and OPcache settings before treating a profile's absolute timings as production timings.