Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent loading time for JS and PHP

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.

like image 262
rationalboss Avatar asked Mar 04 '13 18:03

rationalboss


1 Answers

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

?>
like image 154
Mr. Llama Avatar answered Oct 25 '22 22:10

Mr. Llama