Why is this microtime showing up weird in PHP

后端 未结 4 1514
栀梦
栀梦 2021-01-17 23:52

Why is this microtime showing up weird in PHP

$start4 = microtime(true);
    // run some php code
$end4 = microtime(true);
print \"Time4: \". ($end4 - $start         


        
相关标签:
4条回答
  • 2021-01-18 00:04

    Dont forget float:

    number_format( (float) microtime(true), 10 );
    ------------------^
    

    update: appended to top answer.

    0 讨论(0)
  • 2021-01-18 00:16

    It seems that this microtime() is showing up weird because PHP has a threshold, on either side of which it displays either a number in scientific notation or one in decimal notation. Both of these are technically "floats" (see documentation).

    It seems that this threshold is somewhere between 0.8 seconds and 0.9 seconds; at least that's what my tests concluded. Using the following code will show scientific notation:

    $start4 = microtime(true);
    sleep(0.8);
    $end4 = microtime(true);
    echo 'Time4: ' . ($end4 - $start4) . '<br />';
    

    But if we change our wait time to sleep(0.9), a decimal number is produced. This may or may not be the case on all systems or installations, but this is at least what my tests showed.

    You can counteract this yourself by using the sprintf() function, like this:

    $start4 = microtime(true);
    sleep(0.8);
    $end4 = microtime(true);
    echo 'Time4: ' . sprintf('%f', $end4 - $start4) . '<br />';
    

    This will always show the time as a decimal number.

    0 讨论(0)
  • 2021-01-18 00:22

    E-5 is scientific notation. Seems to happen when you concatenate it with the string value. Try using number_format... ?

    print "Time4: ". number_format($end4 - $start4, 10)."<br />";
    
    //or use:               printf(".10f", $end - $start)
    
    0 讨论(0)
  • 2021-01-18 00:24

    It's normal for long numbers (very small or very large) to be converted to powers of 10. The E-5 just means that the number displayed is beeing multiplied by (10/10/10/10/10) which makes it a very small number.

    0.000000000000123 is much harder to read than 1.23E-13 (for example).

    Nevertheless if you do want to view the number in another format:

    $start = microtime(true);
    $end = microtime(true);
    echo "Time: ", number_format($end - $start, 50);
    

    This will add 50 decimal houses to the number on display.

    Hope it helps!

    0 讨论(0)
提交回复
热议问题