Delay in php sleep functions their selves?

77 Views Asked by At

I have a PHP program that should sleep for some time to make it tick 100 times per 1 second in it's process while loop. But when I want to calculate the time lapsed for a 100 tick cycle I get more than 1 second. Is this a problem from my code or this is a known problem of PHP?

Note: I am using pthreads for my program and the process is running on a Thread that is made by the main Thread.

I am currently using function time_sleep_until() but I also tried usleep() and had the same problem. It does not matter which one is used I just want a precise tps for my program and I am struggling too much with this.

My code:

<?php

class Program extends \Thread {

    private const TPS = 100;

    private int $tickCounter = 0;

    public function run(){
        while(true){
            $start = microtime(true);

            if(($this->tickCounter % self::TPS) === 0){
                $time = round(microtime(true) - $this->tickTime, 3);
                echo "Time per 1 cycle: " . $time . PHP_EOL;
                $this->tickTime = microtime(true);
            }

            // Process some jobs

            $this->tickCounter++;

            $until = microtime(true) - $start;
            if($until < (1 / self::TPS)){
                @time_sleep_until((microtime(true) + (1 / self::TPS)) - $until);
            }
        }
    }
}

$program = new Program();
$program->start(PTHREADS_INHERIT_NONE);

This will take around 1.56sec to cycle 100 ticks while I am not even processing anything as a job. But expected to take 1sec or at least as precise as it can. Also when I put 1 instead of 100 for Program::TPS lapsed time gets 1sec or very close to 1sec.

0

There are 0 best solutions below