dougan1330 2015-10-13 15:51
浏览 31
已采纳

PHP microtime()是正确的吗?

I have used microtime() to check code execution time. But it seems very strange like time tracked is not correct.

So in my test.php, I have code like following:

$debug = true; 
$start = microtime(true); 
$newline = "<br/>";

...

if ($debug) {
    $time_elapsed_secs = microtime(true) - $start;
    $start = microtime(true);
    echo 'Step 1 Done: ' . $time_elapsed_secs . $newline; }

...

if ($debug) {
    $time_elapsed_secs = microtime(true) - $start;
    $start = microtime(true);
    echo 'Step 2 Done: ' . $time_elapsed_secs . $newline; }

Then when I open the URL on browser, it response in less then 1 sec, but it shows something strange value like Step 1 Done: 0.0026565 Step 2 Done: 9.8646454

How come this would happen? Do I do something in wrong way?

  • 写回答

2条回答 默认 最新

  • duanmo5724 2015-10-13 17:37
    关注

    I'm guessing you left a tiny detail out of your description. I think the output you actually saw was more like...

    Step 1 Done: 0.0026565
    ...
    Step 2 Done: 9.8646454E-5
    

    PHP will put floats into scientific notation when they are lower than 0.0001. To make things consistent to read in your output, try changing your code to the following to display the microtimes in decimal notation.

    $debug = true; 
    $start = microtime(true); 
    $newline = "<br/>";
    
    usleep(30);
    
    if ($debug) {
        $time_elapsed_secs = microtime(true) - $start;
        $start = microtime(true);
        echo 'Step 1 Done: ' . sprintf( '%f', $time_elapsed_secs ) . $newline; }
    
    usleep(1);
    
    if ($debug) {
        $time_elapsed_secs = microtime(true) - $start;
        $start = microtime(true);
        echo 'Step 2 Done: ' . sprintf( '%f', $time_elapsed_secs ) . $newline; }
    

    [Note: added usleep() calls to show something happening.]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?