phpdurationmicrotime

Measuring a duration with microtime results randomly in zero


I am having a loop like this:

<?php
ini_set('memory_limit', '16024M');
ini_set('set_time_limit', 9999);
ini_set('max_execution_time', 9999);
ini_set('display_errors',  TRUE);
ini_set('error_reporting',  E_ALL);

for ($k = 1; $k <= 50; $k++) {

    $haystack = array();

    for ($i = 1; $i <= 100; $i++) {

        $randomChar = substr(md5(microtime()),rand(0,26), 1);

        $haystack[] = $randomChar;

    }

    $haystack[] = 'X';

    $startTime = microtime(true);

    // sleep(0);

    $result = in_array('X', $haystack);

    $endTime = microtime(true);

    echo number_format(1000000 * ($endTime - $startTime), 20, ",", " ") . ' ';

 }

And these are the first couple of lines from the output:

1,90734863281250000000 0,95367431640625000000 1,19209289550781250000 1,90734863281250000000 1,19209289550781250000 0,95367431640625000000 0,95367431640625000000 1,90734863281250000000 0,95367431640625000000 20,02716064453125000000 0,95367431640625000000 1,19209289550781250000 0,95367431640625000000 0,95367431640625000000 0,00000000000000000000 0,95367431640625000000 0,95367431640625000000 0,95367431640625000000 0,00000000000000000000 0,95367431640625000000 0,00000000000000000000

As you can see, there are a couple of lines stating a duration of "0" - which is in fact not possible. If I uncomment the line containing the sleep(0) command, there is no zero-duration.

System-Setup

I am running the loop on the CLI and calling it via the Browser.


Solution

  • 101 items in array is small enough for smart php with it's static optimization tricks and powerful cpu.

    If You want to see that 0-s are gone, so generate 1000 items:

    for ($i = 1; $i <= 1000; $i++) {
        $haystack[] = substr(md5(microtime()),rand(0,26), 1);
    }
    

    P.S. I've checked Your code using both 7.1 and 5.6 so there are big differences:

    php7.1 vs php5.6