6

I have a PHP script being loaded by JS through JQuery's $.ajax. I measured the execution time of the PHP script using:

$start = microtime(); // top most part of code
// all other processes that includes AES decryption
$end = microtime(); // bottom part of code
file_put_contents('LOG.TXT','TIME IT TOOK: '.($end-$start)."\n",FILE_APPEND);

It measured somewhere less than 1 second. There are no prepend/append PHP scripts.

In the JS $.ajax code, I have measured the execution time by:

success: function(response) {
    console.log(date('g:i:s a') + ' time received\n');
    // all other processes including AES decryption
    console.log(date('g:i:s a') + ' time processed\n');
}

The time is the same for the time received and the time processed.

However, when I check the Chrome Developer Tools, it claims that the PHP script loaded for about 8 seconds.

What could be wrong in how I measured these things? I'm certain that PHP is loading fast but how come Chrome reports that it took more than 8 seconds?

I'm using localhost and my web server is fast and this is the only time I encountered this problem. All other AJAX calls are fast.

rationalboss
  • 5,330
  • 3
  • 30
  • 50
  • 1
    Make sure you're using floating point `microtime(true)`, otherwise you're doing arithmetic on strings. May not be a solution to your problem, but something you may want to take note of. – Mr. Llama Mar 04 '13 at 19:09
  • That solved it! I spent two hours on this. Could you post your response as answer? So that we can resolve my question. Thank you! – rationalboss Mar 04 '13 at 19:11

1 Answers1

2

In the PHP section, make sure you're using microtime(true) so that you're working with floating point numbers instead of strings. Using subtraction on strings may yield incorrect results.


Example: http://ideone.com/FWkjF2

<?php

// Wrong
$start = microtime();
sleep(3);
$stop  = microtime();
echo ($stop - $start) . PHP_EOL;  // Prints 8.000000000008E-5

// Correct
$start = microtime(true);
sleep(3);
$stop  = microtime(true);
echo ($stop - $start) . PHP_EOL;  // Prints 3.0000791549683

?>
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115