답변:
유닉스 시스템 (및 Windows의 PHP 7 이상)에서는 다음 과 같이 getrusage 를 사용할 수 있습니다 .
// Script start
$rustart = getrusage();
// Code ...
// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";
모든 테스트에 대해 PHP 인스턴스를 생성하는 경우 차이를 계산할 필요가 없습니다.
utime/ stime/ wall 시계 시간에 정확히 어떤 값을 얻 습니까? 이 동작을 보여주는 재현 가능한 예제에 대한 링크를 게시 할 수 있습니까? 어떤 OS / php 버전 / 웹 서버 버전입니까? 어쨌든 새 질문을 게시하고 여기에 링크 할 수 있습니다.
CPU 실행 시간이 아닌 벽시계 시간 만 있으면 다음과 같이 간단하게 계산할 수 있습니다.
//place this before any script you want to calculate time
$time_start = microtime(true);
//sample script
for($i=0; $i<1000; $i++){
//do anything
}
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;
//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
// if you get weird results, use number_format((float) $execution_time, 10)
여기에는 PHP가 max_execution_time에 사용되지 않는 디스크 또는 데이터베이스와 같은 외부 리소스를 기다리는 시간이 포함됩니다.
가장 쉬운 방법 :
<?php
$time1 = microtime(true);
//script code
//...
$time2 = microtime(true);
echo 'script execution time: ' . ($time2 - $time1); //value in seconds
60.로 나누지 않습니다 . 실제로 아무런 차이 가 없습니다 .
<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));
// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did nothing in $time seconds\n";
?>
즉시 사용 가능한 phihag 답변에서 ExecutionTime 클래스를 만들었습니다.
class ExecutionTime
{
private $startTime;
private $endTime;
public function start(){
$this->startTime = getrusage();
}
public function end(){
$this->endTime = getrusage();
}
private function runTime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
public function __toString(){
return "This process used " . $this->runTime($this->endTime, $this->startTime, "utime") .
" ms for its computations\nIt spent " . $this->runTime($this->endTime, $this->startTime, "stime") .
" ms in system calls\n";
}
}
용법:
$executionTime = new ExecutionTime();
$executionTime->start();
// code
$executionTime->end();
echo $executionTime;
참고 : PHP 5에서 getrusage 함수는 Unix-oid 시스템에서만 작동합니다. PHP 7부터는 Windows에서도 작동합니다.
getrusage에서는 PHP 7부터 작동합니다.
developerfusion.com의 Gringod는 다음과 같은 좋은 답변을 제공합니다.
<!-- put this at the top of the page -->
<?php
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
;?>
<!-- put other code and html in here -->
<!-- put this code at the bottom of the page -->
<?php
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "This page was created in ".$totaltime." seconds";
;?>
( http://www.developerfusion.com/code/2058/determine-execution-time-in-php/ )에서
가장 저렴하고 더러운 방법은 microtime()코드에서 벤치마킹하려는 위치를 호출 하는 것입니다 . 데이터베이스 쿼리 직전과 직후에 수행하면 나머지 스크립트 실행 시간에서 해당 기간을 제거하는 것이 간단합니다.
힌트 : PHP 실행 시간이 스크립트 시간을 초과하는 일은 거의 없습니다. 스크립트가 시간 초과되면 거의 항상 외부 리소스를 호출하게됩니다.
PHP 마이크로 타임 문서 : http://us.php.net/microtime
나는 당신이 xdebug를 봐야한다고 생각합니다. 프로파일 링 옵션을 사용하면 많은 공정 관련 항목을 파악할 수 있습니다.
분과 초를 표시하려면 다음을 사용할 수 있습니다.
$startTime = microtime(true);
$endTime = microtime(true);
$diff = round($endTime - $startTime);
$minutes = floor($diff / 60); //only minutes
$seconds = $diff % 60;//remaining seconds, using modulo operator
echo "script execution time: minutes:$minutes, seconds:$seconds"; //value in seconds
남은 실행 시간을 확인하는 함수를 작성했습니다.
경고 : 실행 시간 계산은 Windows 및 Linux 플랫폼에서 다릅니다.
/**
* Check if more that `$miliseconds` ms remains
* to error `PHP Fatal error: Maximum execution time exceeded`
*
* @param int $miliseconds
* @return bool
*/
function isRemainingMaxExecutionTimeBiggerThan($miliseconds = 5000) {
$max_execution_time = ini_get('max_execution_time');
if ($max_execution_time === 0) {
// No script time limitation
return true;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// On Windows: The real time is measured.
$spendMiliseconds = (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]) * 1000;
} else {
// On Linux: Any time spent on activity that happens outside the execution
// of the script such as system calls using system(), stream operations
// database queries, etc. is not included.
// @see http://php.net/manual/en/function.set-time-limit.php
$resourceUsages = getrusage();
$spendMiliseconds = $resourceUsages['ru_utime.tv_sec'] * 1000 + $resourceUsages['ru_utime.tv_usec'] / 1000;
}
$remainingMiliseconds = $max_execution_time * 1000 - $spendMiliseconds;
return ($remainingMiliseconds >= $miliseconds);
}
사용 :
while (true) {
// so something
if (!isRemainingMaxExecutionTimeBiggerThan(5000)) {
// Time to die.
// Safely close DB and done the iteration.
}
}
$_SERVER['REQUEST_TIME']그것도 확인하십시오. 즉
...
// your codes running
...
echo (time() - $_SERVER['REQUEST_TIME']);
$_SERVER['REQUEST_TIME']도 php-cli (서버가없는 곳)에서도 가능합니다
스크립트 부분의 실행 시간 만 알고 싶을 수도 있습니다. 부분 또는 전체 스크립트를 시간에 가장 유연하게 적용하는 방법은 간단한 함수 3 개를 작성하는 것입니다 (프로 시저 코드는 여기에 있지만 클래스 타이머 {}를 둘러싼 후 몇 가지 조정하면 클래스로 바꿀 수 있습니다). 이 코드는 복사하여 붙여 넣은 다음 작동합니다.
$tstart = 0;
$tend = 0;
function timer_starts()
{
global $tstart;
$tstart=microtime(true); ;
}
function timer_ends()
{
global $tend;
$tend=microtime(true); ;
}
function timer_calc()
{
global $tstart,$tend;
return (round($tend - $tstart,2));
}
timer_starts();
file_get_contents('http://google.com');
timer_ends();
print('It took '.timer_calc().' seconds to retrieve the google page');
대안으로 코드 블록 에이 줄을 넣고 PHP 로그를 확인할 수 있습니다. 실제로 느린 기능에 대해서는 매우 유용합니다.
trigger_error("Task done at ". strftime('%H:%m:%S', time()), E_USER_NOTICE);
XDebug + Cachegrind를 사용하는 심각한 디버깅에 대해서는 https://blog.nexcess.net/2011/01/29/diagnosing-slow-php-execution-with-xdebug-and-kcachegrind/를 참조 하십시오.
Hamid의 답변을 더 확장하면서 루프에서 프로파일 링하기 위해 반복적으로 시작하고 중지 할 수있는 도우미 클래스를 작성했습니다.
class ExecutionTime
{
private $startTime;
private $endTime;
private $compTime = 0;
private $sysTime = 0;
public function Start(){
$this->startTime = getrusage();
}
public function End(){
$this->endTime = getrusage();
$this->compTime += $this->runTime($this->endTime, $this->startTime, "utime");
$this->systemTime += $this->runTime($this->endTime, $this->startTime, "stime");
}
private function runTime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
public function __toString(){
return "This process used " . $this->compTime . " ms for its computations\n" .
"It spent " . $this->systemTime . " ms in system calls\n";
}
}