Sleeping the time difference

241 Views Asked by At
$lastRequestTimestamp = microtime(true);
if (microtime(true) - $lastRequestTimestamp < 1) {
  sleep(1);
}
$lastRequestTimestamp = microtime(true);

// now continue with the request ... 

... works, but if the difference is even a few milliseconds, it sleeps for 1 second which is significant considering the number of requests I have to make.

How do I make the script sleep only so much that there's always exactly 1 sec delay between requests, no less no more.

2

There are 2 best solutions below

0
On BEST ANSWER
$timeDifferenceSecs = (microtime(true) - $lastRequestTimestamp);
$sleepMicrosecs = (1 - $timeDifferenceSecs)*1000000;
usleep($sleepMicrosecs);
2
On

You can use the usleep function instead, this way you can sleep for microseconds instead of complete seconds.