Search code examples
phptimerevalxmlreadermicrotime

PHP microtime strange behavior


I was looking at execution time of some functions, but i have found that microtime is getting wrong, in one microtime()

implementation №1 always first time is always getting more then second microtime() executing, when i testing one function and saw that one case is faster then another, but after place replace (2nd function to 1st place), it getting slower anyway, even if it was 3x faster...

function dotimes($times,$eval,$data=false) {for(;--$times;) eval($eval);}


$start = microtime(true);

dotimes(1000,'$i = $i?$times/2:1;');

printf(": executed : %f\n",microtime(true)-$start);

$start = microtime(true);

dotimes(1000,'$i = $i?$times/2:1;');

printf(": executed : %f\n",microtime(true)-$start);

// 1st case is always slower...

implementation №2 iv made sometimes before microtime() as static data storage, but in that case the time of execute is always second time is slower then first (oposite to implementation №1)

function get_execution_time()
{
    static $microtime_start = null;

        return $microtime_start === null ? $microtime_start = microtime(true) : microtime(true) - $microtime_start;

}


function dotimes($times,$eval,$data=false) {for(;--$times;) eval($eval);}

get_execution_time();
dotimes(1000,'$i = $i?$times/2:1;');

printf(": executed : %f\n<br>",get_execution_time());
get_execution_time();
dotimes(1000,'$i = $i?$times/2:1;');
printf(": executed : %f\n<br>",get_execution_time());
//now 2nd case is faster..
  • Can somebody tell me what is going up? Why these microtimes in one case 1st always slower, and throught static storage 2nd execute is slow down, WHY?

ps if someone need tiny mt function here is my FIXED AND WORKING CORRECT:

function get_mt() {static $mt; return $mt ? microtime(true)-$mt.$mt=null : $mt=microtime(true);}

attached :

function get_mt() {static $mt; return $mt?microtime(true)-$mt:$mt=microtime(true);}

function dotimes($times,$eval,$data=false) {for(;--$times;) eval($eval);}

$start = microtime(true);
get_mt();
dotimes(10000,'$i = $i?$times/2:1;');
printf(":clean executed : %f\n<br>",microtime(true)-$start);
printf(":static executed : %f\n<br>",get_mt());
$start = microtime(true);
get_mt();
dotimes(10000,'$i = $i?$times/2:1;');
printf(":clean executed : %f\n<br>",microtime(true)-$start);
printf(":static executed : %f\n<br>",get_mt());

Solution

  • So far, I see that implementation №1 is correct. No clue what you tried in your second implementation.

    The advice here - never test two cases in the same script. Run them separately a few times and then find the average time. PHP allocates memory when it needs and this is a slow operation. The second case may reuse already allocated memory and skip this operation and you get wrong results.