A
A
Alex2014-04-07 14:45:55
PHP
Alex, 2014-04-07 14:45:55

How to make script execution delay < 10 milliseconds?

There is a loop, inside the usleep() function pauses the execution of each iteration for a given number of microseconds (millionths of a second). I want the script to pause for 10 milliseconds (i.e. 10 thousandths of a second). Looks like this:

for($i = 1; $i <= 1000; $i ++){
    /*
    * какой-то код
    */
    usleep(10000); //это 0,010 секунды
}

The problem is that a delay of 10 and less than 10 milliseconds does not work, at least 20 milliseconds. Here's what they write about on the topic :
Delays of less than 50 milliseconds (depending on the speed of the processor, machine, and system load) are not possible, because. it takes at least 10-30 milliseconds to return control to a process in Linux. Specifying such delays for usleep(3) will actually result in a longer delay (at least 10ms).
Question: Is it possible to reduce the delay in usleep() to less than 10 milliseconds? What about time_nanosleep(), where a delay of 1 billionth of a second is possible? The server is on FreeBSD 9.1

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Morozov, 2014-04-07
@b1nary

$lastTime = microtime(true);

for($i = 1; $i <= 1000; $i ++){
    while (true)
    {
           $new_last = microtime(true);
           if ($new_last - $lastTime > 0.010)
           {
                    $lastTime = $new_last;
                    break;
           }
    }

    /*
    * какой-то код
    */
}

D
Denis Morozov, 2014-04-07
@morozovdenis

I became curious, php went to remember
this code from me:

var_dump(number_format(microtime(true), 6));
time_nanosleep(0, 10 * 1000 * 1000);
echo "<br />";
var_dump(number_format(microtime(true), 6));
output the following:
string(20) "1,396,895,032.113305" 
string(20) "1,396,895,032.123673"

time_nanosleep - put everything to sleep for 10 milliseconds

J
jcmvbkbc, 2014-04-08
@jcmvbkbc

How then is time_nanosleep() where a delay of 1 billionth of a second is possible

Who told you? You can specify the desired time with an accuracy of 1ns, but what the actual delay will be depends on very, very many factors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question