1

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.

Sam
  • 7,252
  • 16
  • 46
  • 65
NotGaeL
  • 8,344
  • 5
  • 40
  • 70
  • 4
    Out of interest why do you want to sleep? (I'm just curious if you have a bigger issue that could be solved differently) ;-) – scunliffe Sep 09 '13 at 02:53
  • 1
    There isn't much you can do. `usleep` does no guarantee at all that your script will be awakened precisely after that amount of time; instead it says that it will sleep for *at least* that long, and that the actual duration may be increased because of system latencies and possible limitations in timer resolution. Then add PHP's overhead to that. – zneak Sep 09 '13 at 02:59
  • I'm trying to generate real time events for a simulation, so I can test my web application's performance (the app tracks, processes and displays changes on a log file in real time). An overhead of a thousand times seems quite a lot... – NotGaeL Sep 09 '13 at 03:00

1 Answers1

1

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.

david25272
  • 976
  • 6
  • 12
  • Well this is definitely the problem (I tried C code using `usleep` and `clock_gettime` with the same results) but the article didn't help me much. Since I am using virtualization on a windows host I apparently have a lower resolution (like 7.5ms) but it's still a lot more than I'm actually getting. What do I need, a real time Kernel for this? – NotGaeL Sep 13 '13 at 15:01