Electronic Elves Residence
Add
{code} {code} == == * * _ _ [] * #

203

2017-01-12 12:44:27
class defer {
        private $cb;
        public function __construct($cb) {$this->cb = $cb;}
        public function __destruct() {$cb = $this->cb; $cb();}
}

$log_id = \Logs::addLog(CLASS_DB, new \LogScreen());
$defer = new \defer(function() use ($log_id) { \Logs::delLog(CLASS_DB, $log_id);});

function cpusleep($cpu_time) {
    $cur = $prev_cur = $start = microtime(true);
    $cycle_time = 1e-5;
    $cycles = 1;
    $cycle_time_reaction = 1;

    while (($left = $cpu_time - ($cur - $start)) > 0) {
        $cycle_time = ($cycle_time + ($cur - $prev_cur) / $cycles) * $cycle_time_reaction / (1 + $cycle_time_reaction);
        $cycles = $left / $cycle_time;
        for ($i = 0; $i < $cycles; $i++);
        $prev_cur = $cur;
        $cur = microtime(true);
    }
}

function ru($msg, $ru_param = null) {
    $ru = $ru_param !== null ? getrusage($ru_param) : getrusage();
    echo "$msg:" . ($ru['ru_utime.tv_sec'] * 1e6 + $ru['ru_utime.tv_usec']) . "\n";
}

function sleep_period($epoch_period) {
        $now_ms = microtime(true) * 1000;
        $epoch_ms = (((int)($now_ms / $epoch_period)) + 1) * $epoch_period;
        usleep(($epoch_ms - $now_ms) * 1000);
}