Search code examples
phpdatetimedateinterval

How to benchmark code to see which runs faster


$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');

Can anyone tell me which is faster, recommended and takes less memory in huge operations in php file. I think its DateInterval PID. Any experienced developer?


Solution

  • To benchmark code, you can use microtime()

    http://php.net/manual/en/function.microtime.php

    <?php
    
    echo 'modify: ';
    $time = microtime(1);
    for ($x = 0; $x < 10000; $x++) {
        $datetime = new DateTime('2013-01-29');
        $datetime->modify('+1 day');
    }
    echo $datetime->format('Y-m-d H:i:s'); 
    $end = microtime(1);
    $time = $end - $time;
    echo $time . "\n";
    
    echo 'interval: ';
    $time = microtime(1);
    for ($x = 0; $x < 10000; $x++) {
        $datetime = new DateTime('2013-01-29');
        $datetime->add(new DateInterval('P1D'));
    }
    $end = microtime(1);
    $time = $end - $time;
    echo $time . "\n";
    

    This outputs :

    modify: 0.039623975753784 
    interval: 0.036103963851929
    

    As you can see, after performing the calculation 10,000 times on each, DateInterval is the faster code. However, this is what I would call a microoptimisation! There isn't much difference!

    See it working here https://3v4l.org/pCecn