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

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

  •  28-06-2022
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top