1

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?

Codemole
  • 2,649
  • 4
  • 19
  • 40
  • "Step 1 Done: 0.0026565" means that it took 0.0026565 seconds to get to that point. "Step 2 Done: 9.8646454" means that it took 9.8646454 seconds to get to that point. – samlev Oct 13 '15 at 15:57

2 Answers2

2

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

BA_Webimax
  • 2,651
  • 1
  • 11
  • 15
1

It depends what does the code between the two steps. Comment out the code between the two steps and (but you are right it is strange if the page returns less than 1 sec.. )

// Sleep for a while
usleep(100);

Check if microtime measures the correct time delta.

C1sc0
  • 1,378
  • 4
  • 24
  • 29