how can I effectively put my script to sleep for an accurate amount of miliseconds?

StackOverflow https://stackoverflow.com/questions/18690803

  •  28-06-2022
  •  | 
  •  

Question

I wrote the following myscript.php:

<?php
$count=0;
$start=microtime(true);
while ((microtime(true)-$start)<1) {
        usleep(1000);
        $count++;
}
echo $count;
?>

Instead of a number close to 1000, when I run php -f myscript.php on my CentOS 2.6.32 x64 kernel (windows 7 host) I get outputs like 35,43,76,543,44,39,29,38... What can I do?

EDIT: I also tried time_nanosleep(0,1000000) and C code using usleep() and clock_gettime() instead, with the same results.

Était-ce utile?

La solution

It could be overhead in PHP, or it could be that microtime() and usleep() in PHP aren't that accurate. It would be interesting to see what similar code in C does.

This article has an interesting discussion on accurate timing.

And this article by VMWare on timing in virtual machines may be of interest.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top