Question

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?

Was it helpful?

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.

OTHER TIPS

This might be wrong, but I remember a long time ago someone telling me that time on computers is very hard to measure.

Considering that calling the functions sleep() and microtime() all take some time it will always be out. There is an overhead in doing anything which won't be part of the timing process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top