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?
Definition of microtime : a very short interval of time (as 0.01 millionth of a second) microtime photography.
The time() function is a built-in function in PHP which returns the current time measured in the number of seconds since the Unix Epoch. The number of seconds can be converted to the current date using date() function in PHP. Syntax: int time() Parameter: This function does not accepts any parameters as shown above.
Return Value: It returns timestamp based unique identifier as a string. Errors And Exceptions: The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly.
The microtime() function returns the current Unix timestamp with microseconds.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With