0

I have a variable ($i) starts from 0 to 9. It keeps increasing ($i++) in a loop until it reaches 9, when it reaches 9 it sets back $i to 0. I want to run this loop for 2 seconds only and then get the final number where it stopped after 2 seconds. So I wrote the following code:

$now = time();
$counter = 0;
while ($now + 2 > time()) {
    $counter++;
    if($counter == 9)
        $counter = 0;
}
echo 'Counter: '.$counter;

However this is inaccurate, every time it runs for 2 seconds, number is different. How can I use usleep(2000000); which I read is more accurate in while() or for() loop and break the loop and print the $counter number with accuracy.

Themer
  • 185
  • 1
  • 12
  • 1
    1. Microtime is going to get you closer to actually being 2 seconds. 2. I don't believe you can depend on PHP to execute a counter increase, time determination, and greater than indicator (besides your other things) in *exactly* the same time as it took the last time, for probably well over a million times, so your result will never be consistent. – forrestmid Mar 04 '18 at 21:08
  • 1
    What is the real goal? If you a are looking for something deterministic basing it on time may not be the best approach. – Jtbs Mar 04 '18 at 21:15
  • 1
    You would need to measure how long the logic takes, then skim that off the sleep time. And perhaps use time_sleep_until to start on the next second or if you start between seconds your loose that. Seems overkill for a loop which counts to 2 ;p – Lawrence Cherone Mar 04 '18 at 21:16

0 Answers0