Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php microtime explanation

Tags:

php

microtime

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?

like image 323
Adam Avatar asked Dec 04 '11 23:12

Adam


People also ask

What is a Microtime?

Definition of microtime : a very short interval of time (as 0.01 millionth of a second) microtime photography.

What is PHP time function?

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.

Is PHP timestamp unique?

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.

How can I get MS in PHP?

The microtime() function returns the current Unix timestamp with microseconds.


2 Answers

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.

like image 153
landons Avatar answered Oct 08 '22 00:10

landons


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.

like image 25
Jake N Avatar answered Oct 07 '22 23:10

Jake N