How to measure function execution time in PHP

3 Answers

0 votes
// Measuring execution time using microtime(true)

// A sample function to measure
function work() {
    $sum = 0;
    for ($i = 0; $i < 100000000; $i++) {
        $sum += $i;
    }
}

// Record start time (in seconds with microsecond precision)
$start = microtime(true);

work();

// Record end time
$end = microtime(true);

// Compute elapsed time
$elapsedSeconds = $end - $start;
$elapsedMilliseconds = $elapsedSeconds * 1000;

echo "Execution time: {$elapsedMilliseconds} ms\n";
echo "Execution time: {$elapsedSeconds} seconds\n";



/* 
run:

Execution time: 390.32816886902 ms
Execution time: 0.39032816886902 seconds

*/

 



answered 4 hours ago by avibootz
0 votes
// Measuring execution time using hrtime(true)

// A sample function to measure
function work() {
    $sum = 0;
    for ($i = 0; $i < 100000000; $i++) {
        $sum += $i;
    }
}

// Start timer (nanoseconds)
$start = hrtime(true);

work();

// End timer
$end = hrtime(true);

$elapsedNano = $end - $start;
$elapsedMilliseconds = $elapsedNano / 1_000_000;
$elapsedSeconds = $elapsedNano / 1_000_000_000;

echo "Execution time: {$elapsedMilliseconds} ms\n";
echo "Execution time: {$elapsedSeconds} seconds\n";



/* 
run:

Execution time: 388.360076 ms
Execution time: 0.388360076 seconds

*/

 



answered 4 hours ago by avibootz
0 votes
// Measuring execution time using a reusable Timer class

class Timer {
    private float $start;
    private float $end;

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

    public function stop(): void {
        $this->end = microtime(true);
    }

    public function elapsedMilliseconds(): float {
        return ($this->end - $this->start) * 1000;
    }

    public function elapsedSeconds(): float {
        return $this->end - $this->start;
    }
}

// A sample function to measure
function work() {
    $sum = 0;
    for ($i = 0; $i < 100000000; $i++) {
        $sum += $i;
    }
}

$timer = new Timer();

$timer->start();
work();
$timer->stop();

echo "Execution time: " . $timer->elapsedMilliseconds() . " ms\n";
echo "Execution time: " . $timer->elapsedSeconds() . " seconds\n";



/* 
run:

Execution time: 386.60883903503 ms
Execution time: 0.38660883903503 seconds

*/

 



answered 4 hours ago by avibootz
...