Self-regulation sleep-loop in php



  • We've got to do something through the time frames set:

    while (1) {
      // некое действие
      echo microtime(1)."\n";
      time_nanosleep(1, 000000000);
    }
    

    as the operation takes place at one time, removes:

    1449084599.4376
    1449084600.439
    1449084601.4402
    1449084602.4414
    1449084603.4427
    

    I mean, we don't act at a given interval, but less. How do you adjust time to act once a second?

    $oldt = microtime(1);
    while (1) {
      $newt = microtime(1);
      // некое действие
      time_nanosleep(0, 1000000000 - $newt + $oldt);
      $oldt = $newt;
    }
    

    It's kind of fascinating, but logic shows that the error is about the same.



  • On the basis of a micro-time, you can calculate an adjustment that can be given sleep. Only the guarantees will no-one provide, by adjusting to say, that in 10 seconds the operation would have been done exactly 10 times. But a small plus minus between operations would still be the same, but the computer process is not the only one working, the processor may be occupied at the right moment. And the LO core can't trigger the process to a millisecond. In addition, on modern computers, the processor may be engaged in the implementation of the code of no uncontrolled operating system.

    This is an example:

     $start=microtime(1);
     $iter=0;
     while (1) {
       // действие
      $tm=microtime(1);
      $sleep=(1-($tm-($start+$iter)))*1000000000;
      echo $tm."\n";
      time_nanosleep(0,$sleep);
      $iter++;
     }
    

    Gives about that result:

    1449086740.7135
    1449086741.7073
    1449086742.7028
    1449086743.7031
    1449086744.7058
    ...
    1449086811.7023
    1449086812.7025
    1449086813.6991
    1449086814.7001
    1449086815.702
    1449086816.7025
    1449086817.7029
    1449086818.7023
    

    As you can see, there's a fluctuation, but there's a million-seconds to hold on about one level. I consider the time-use approach from the beginning of the cycle multiplied by the number of completed cycles to be much more precise than the calculation of the time of one cycle. So the timer values also have fluctuation, at least because of rounding float, where the time is stored for iron-related reasons in the OS.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2