programing

타이머 시작 및 중지 PHP

minimums 2023. 8. 26. 10:40
반응형

타이머 시작 및 중지 PHP

저는 PHP에서 타이머를 시작하고 중지하는 것에 대한 정보가 필요합니다..exe 프로그램 시작부터 경과 시간을 측정해야 합니다(사용 중)exec()실행이 완료되고 몇 초 안에 소요된 시간이 표시될 때까지 (내 php 스크립트에서 함수).

어떻게 해야 하나요?

사용할 수 있습니다.microtime차이를 계산합니다.

$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;

다음은 PHP 문서입니다.microtime: http://php.net/manual/en/function.microtime.php

PHP 7.3 이후에는 계측에 hrtime 함수를 사용해야 합니다.

$start = hrtime(true);
// run your code...
$end = hrtime(true);   

echo ($end - $start);                // Nanoseconds
echo ($end - $start) / 1000000;      // Milliseconds
echo ($end - $start) / 1000000000;   // Seconds

언급된 마이크로타임 함수는 시스템 클럭에 의존합니다.예를 들어 Ubuntu의 ntpd 프로그램이나 sysadmin에 의해 수정될 수 있습니다.

함수를 사용합니다.설명서에는 예제 코드가 포함되어 있습니다.

목적을 위해 필요한 것은 다음과 같은 간단한 수업뿐입니다.

class Timer {
    private $time = null;
    public function __construct() {
        $this->time = time();
        echo 'Working - please wait..<br/>';
    }

    public function __destruct() {
        echo '<br/>Job finished in '.(time()-$this->time).' seconds.';
    }
}


$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in n seconds." n = seconds elapsed

타이머 클래스를 사용할 수 있습니다.

    <?php

class Timer {

   var $classname = "Timer";
   var $start     = 0;
   var $stop      = 0;
   var $elapsed   = 0;

   # Constructor
   function Timer( $start = true ) {
      if ( $start )
         $this->start();
   }

   # Start counting time
   function start() {
      $this->start = $this->_gettime();
   }

   # Stop counting time
   function stop() {
      $this->stop    = $this->_gettime();
      $this->elapsed = $this->_compute();
   }

   # Get Elapsed Time
   function elapsed() {
      if ( !$elapsed )
         $this->stop();

      return $this->elapsed;
   }

   # Resets Timer so it can be used again
   function reset() {
      $this->start   = 0;
      $this->stop    = 0;
      $this->elapsed = 0;
   }

   #### PRIVATE METHODS ####

   # Get Current Time
   function _gettime() {
      $mtime = microtime();
      $mtime = explode( " ", $mtime );
      return $mtime[1] + $mtime[0];
   }

   # Compute elapsed time
   function _compute() {
      return $this->stop - $this->start;
   }
}

?>

또한 HR Time 패키지를 사용할 수 있습니다.클래스 StopWatch가 있습니다.

class Timer
{
    private $startTime = null;

    public function __construct($showSeconds = true)
    {
        $this->startTime = microtime(true);
        echo 'Working - please wait...' . PHP_EOL;
    }

    public function __destruct()
    {
        $endTime = microtime(true);
        $time = $endTime - $this->startTime;

        $hours = (int)($time / 60 / 60);
        $minutes = (int)($time / 60) - $hours * 60;
        $seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
        $timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));

        echo 'Job finished in ' . $timeShow . PHP_EOL;
    }
}

$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in h:m:s"

대신 php에는 타이머 컨트롤러가 내장되어 있습니다.new EvTimer().

특수한 경우를 적절하게 처리하여 작업 스케줄러를 만드는 데 사용할 수 있습니다.

이것은 시간뿐만 아니라 시간 전송 레이어, 크로노미터, 랩 카운터, 마치 스톱워치처럼 php 콜백이 있습니다 ;)

EvTimer 감시기는 주어진 시간 이후에 이벤트를 생성하는 단순한 상대 타이머이며, 선택적으로 그 이후에 정기적으로 반복됩니다.

타이머는 실시간을 기준으로 합니다. 즉, 한 시간 후에 시간 초과되는 이벤트를 등록하고 시스템 시계를 작년 1월로 재설정해도 한 시간 후에도 여전히 시간 초과됩니다.

콜백은 제한 시간(...)이 경과한 후에만 호출됩니다.동일한 루프 반복 중에 여러 타이머가 준비되는 경우, 시간 초과 값이 더 이른 타이머가 나중의 시간 초과 값과 동일한 우선 순위의 타이머보다 먼저 호출됩니다.

타이머 자체는 드리프트를 방지하기 위해 최선을 다합니다. 즉, 타이머가 10초마다 트리거되도록 구성된 경우 일반적으로 정확히 10초 간격으로 트리거됩니다.그러나 10초 이상이 소요되어 스크립트가 타이머를 따라잡을 수 없는 경우) 이벤트 루프 반복마다 타이머가 두 번 이상 실행되지 않습니다.

처음 두 매개 변수를 사용하면 실행 전의 시간 지연과 반복 횟수를 제어할 수 있습니다.

세 번째 매개 변수는 각 반복에서 호출되는 콜백 함수입니다.

after

    Configures the timer to trigger after after seconds.

repeat

    If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
    If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

https://www.php.net/manual/en/class.evtimer.php

https://www.php.net/manual/en/evtimer.construct.php

$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

수 .sleep(),usleep()또는hrtime(),그렇지만new EvTimer()에서는 중첩과 같은 특수한 경우를 처리하면서 여러 통화를 정리하고 구성할 수 있습니다.

언급URL : https://stackoverflow.com/questions/8310487/start-and-stop-a-timer-php

반응형