4

While trying to compare algorithm running time in PHP, I came across the microtime() function. But I think there's something fundamental I've missed in understanding. The difference of two microtime(true) calls returns the result in seconds, right? Then consider this extremely simple script:

$t1 =  microtime(true);
//do nothing
$t2 = microtime(true);

echo ($t2 - $t1);

When I run this script several times, I get values varying between 1.19 seconds and 3.5 seconds. This is clearly wrong, as the page reload is instant and there's absolutely nothing for the script to do.

What am I doing wrong?

ankush981
  • 5,159
  • 8
  • 51
  • 96
  • This question will probably be closed as a duplicate soon. If the answers from the duplicates don't fully address your question please edit it to include why and flag this for re-opening. Thanks! [Look here](http://stackoverflow.com/questions/6245971/accurate-way-to-measure-execution-times-of-php-scripts) – Rohit Gupta Jun 21 '15 at 07:52
  • @RohitGupta Okay, but I've sifted through many similar answers. My point is why it takes 1-3 seconds for the script to do nothing. – ankush981 Jun 21 '15 at 07:54
  • possible duplicate of [Tracking the script execution time in PHP](http://stackoverflow.com/questions/535020/tracking-the-script-execution-time-in-php) – Achrome Jun 21 '15 at 08:08

2 Answers2

4

You must be misreading the result, which is for example:

2.1457672119141E-6
  • 2.14 millionth of a second, not 2,14 seconds.

http://sandbox.onlinephpfunctions.com/code/5aa27a5fa9a228fd66eb08f0bb49384fc5b840d9

n-dru
  • 9,285
  • 2
  • 29
  • 42
3

Calculations (with the parameter get_as_float as true) will give you results in seconds, according to PHP documentation.

By default, microtime() returns a string in the form "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also expressed in seconds.

If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

For full text refer here http://php.net/manual/en/function.microtime.php

On top of that your OS is doing lots of things in between.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
  • Hmm . . . I dug up a lot of official documentation, but never thought about the OS angle. Does that mean I can never have an accurate estimate of running time of a code section? It seems to me that depending on the OS, selection sort, for example, might turn out to be more efficient than quicksort sometimes! Do you agree? – ankush981 Jun 21 '15 at 08:01
  • His answer is now deleted, but he wrote of milliseconds, which I find nowhere in the documentation. Anyway . . . – ankush981 Jun 21 '15 at 08:39