php microtime explanation
Asked Answered
B

2

10

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?

Barbell answered 4/12, 2011 at 23:45 Comment(8)
Why do you need to do this? Is it just an experiment, or a real use case?Battement
One of the reasons is that you don't use a realtime operating system.Backspin
i am benchmarking my site and with these kind of results, i cannot say i am 100% accurate, specially if my script is bigger (that is just an example - my script takes 3 seconds to run - its a cronjob im trying to optimize)Barbell
what do you mean by realtime operating system?Barbell
Is Time 4 meant to be 4.004211?Dorella
@Barbell long answer: ece.cmu.edu/~koopman/des_s99/real_time short answer: en.wikipedia.org/wiki/…Redoubt
oh yes, bad copy and paste thanksBarbell
Even if it was a realtime operating system it wouldn't give guarantees at the microsecond level. There would always be variation on that level.Finley
U
17

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.

Unawares answered 4/12, 2011 at 23:48 Comment(1)
+1 The CPU / kernel aren't even going to guarantee that the next microtime won't be delayed for seconds if the computer is very busy. All sleep does is pause script execution for a minimum of the time specified.Redoubt
N
5

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.

Neslund answered 4/12, 2011 at 23:50 Comment(1)
Time is easy to measure. Getting an ACCURATE reating is the hard part. By the time the clock system interrupt gets noticed and processed by the OS, the time that triggered the interrupt has already gone past.Paleopsychology

© 2022 - 2024 — McMap. All rights reserved.