phpmicrotime

php microtime explanation


I have this code:

$time_sample[] = microtime(true); //start
sleep(1);
$time_sample[] = microtime(true); //time 1
sleep(2);
$time_sample[] = microtime(true); //time 2
sleep(3);
$time_sample[] = microtime(true); //time 3
sleep(4);
$time_sample[] = microtime(true); //time 4

The script outputs:

Time 1: 1.001217 seconds.
Time 2: 2.002094 seconds.
Time 3: 3.003023 seconds.
Time 4: 4.004211 seconds.

Based on this, why is sleep(1) not 1.000000 second, sleep(2) 2.00000 seconds and so on?

I did the same test with usleep() and I get the same type of results.

Can you please explain to me why?


Solution

  • It still takes extra overhead for function calls and variable assignment, etc. It will be AT LEAST the length of time you sleep, probably a few milliseconds more.