How can I measure the speed of code written in PHP?

How can I measure the speed of code written in PHP?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Measuring PHP Execution Speed: Beyond Gut Feelings

When you have multiple implementations of the same logic, relying on intuition or var_dump is rarely sufficient to determine which class executes faster. To get a reliable answer, you need to move from qualitative observation to quantitative measurement. The standard tool for this in the PHP ecosystem is the built-in micro-benchmarking capabilities provided by the engine itself, specifically functions like microtime(true) and hrtime() (available since PHP 7.3).

However, simply wrapping code in a timer isn't enough if you aren't careful about how you execute it. The most common pitfall is measuring only once or running the test too few times. Modern CPU caches and JIT compilers can skew results on single runs. A valid benchmark requires repetition to average out noise caused by garbage collection cycles, memory allocation spikes, or context switching.

Isolating the Variables

Before writing any code, you must ensure that external factors don't influence your metrics. If your test runs alongside other processes on a shared server, network latency or I/O operations will inflate your numbers. The goal is to isolate the specific method or function you are comparing.

To achieve this, clear memory between iterations. PHP's garbage collector can trigger unpredictably during long loops, pausing execution. You can hint to the engine to run before every iteration using gc_collect_cycles(), though this adds overhead. For high-precision measurements, it is often better to disable the GC entirely within the scope of your test:

gc_disable(); // Disable GC for the duration of the benchmark

Remember to re-enable it afterward, or wrap the logic in a separate process to avoid polluting the main application state.

Implementing a Robust Benchmark Loop

A robust benchmark loop runs the target code thousands of times. Let's assume you have two classes, ClassA and ClassB, that perform an identical task. You want to know which one wins.

Start by defining a function that accepts the class name or instance as an argument. This allows for dynamic swapping without rewriting the test suite.

function benchmark($object, $methodName = 'execute', $iterations = 10000) {
    gc_disable();
    
    $start = microtime(true);
    
    for ($i = 0; $i < $iterations; $i++) {
        $object->$methodName();
    }
    
    $end = microtime(true);
    gc_enable(); // Re-enable GC if it was disabled
    
    return round(($end - $start) / $iterations * 1000, 3); // Return in milliseconds
}

This function calculates the average time per execution by dividing the total duration by the number of iterations. The result is returned in milliseconds for readability. If you need nanosecond precision (using hrtime()), ensure your PHP version supports it, though milliseconds are often sufficient for macro-level comparisons unless you are optimizing a micro-operation like string parsing.

Handling Trade-offs and Pitfalls

There is a significant trade-off between accuracy and execution time. Running 100,000 iterations provides high statistical confidence but takes longer to run the test itself. If your code performs an I/O operation (like a database query) inside the loop, you might accidentally measure network latency rather than CPU processing speed. In such cases, ensure that the data is already cached or mocked during the benchmark phase.

Another critical detail is memory usage. Even if execution time is fast, one class might consume significantly more RAM than another. A slower class with low memory footprint might be preferable to a faster class that causes frequent garbage collection pauses in production. Always pair timing metrics with memory profiling tools like Xdebug's profiler or Blackfire.io for a complete picture.

Integrating Results into Your Workflow

When comparing classes, the goal is rarely just to find the fastest one in a vacuum; it is to find the one that offers the best balance of speed and maintainability. Micro-optimizations often yield diminishing returns. If two implementations differ by less than 5% in execution time, choose the one with clearer logic or better documentation.

For production environments where you need continuous performance monitoring, consider integrating these benchmarks into your CI/CD pipeline. Automated tests can run your benchmark suite on every commit, alerting you immediately if a recent change degrades performance. This prevents "regression" bugs where a new feature inadvertently slows down existing functionality.

If you are building a complex Laravel application and need deeper insights into query performance or routing bottlenecks, tools like LaravelDebugbar or specific tracing middleware can provide granular data beyond simple execution timers. For enterprise-level needs, visiting the official LaravelCompany.com resources can offer further guidance on scaling PHP applications effectively.

Ultimately, measuring speed is about controlling your test environment and repeating the experiment enough times to trust the numbers.

Our network