How To Time Php

When working on performance-critical PHP applications, it’s often necessary to measure the execution time of different functions or scripts. In this post, we’ll discuss how to time PHP functions efficiently and how to format the output for better understanding.

Using microtime()

The most common method to time PHP functions is by using the microtime() function. This function returns the current Unix timestamp with microseconds, allowing us to measure time intervals with sub-second precision.

Here’s a basic example of how to measure the execution time of a function using microtime():

$start_time = microtime(true);

function_to_time();

$end_time = microtime(true);
$total_time = $end_time - $start_time;

echo "Execution time: " . $total_time . " seconds";

Creating a Timer Class

For better code organization and reusability, you can create a simple Timer class that can be used to time different parts of your PHP application. Here’s a basic example of a Timer class:

class Timer {
    private $start_time;

    public function start() {
        $this->start_time = microtime(true);
    }

    public function stop() {
        return microtime(true) - $this->start_time;
    }
}

You can use this class to time your functions as follows:

$timer = new Timer();
$timer->start();

function_to_time();

$total_time = $timer->stop();
echo "Execution time: " . $total_time . " seconds";

Formatting the Output

The execution time returned by microtime() is in seconds and has a high precision. You may want to format this output for better readability, such as converting it to milliseconds, and rounding to a certain number of decimal places. You can do so by using the number_format() function. Here’s an example:

$total_time_ms = $total_time * 1000;
$rounded_total_time_ms = number_format($total_time_ms, 2);

echo "Execution time: " . $rounded_total_time_ms . " milliseconds";

Conclusion

In this blog post, we discussed how to time PHP functions efficiently using the microtime() function and how to create a reusable Timer class. We also discussed how to format the output for better readability. By using these techniques, you can easily track the performance of your PHP applications and make informed decisions when optimizing your code.