Search code examples
phpmicrotime

PHP microtime() is correct?


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?


Solution

  • 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.]