Hướng dẫn dùng execution timer trong PHP

answer

195

Hướng dẫn dùng execution timer trong PHP

Trên các hệ thống unixoid (và trong php 7+ trên Windows), bạn có thể sử dụng getrusage , như:

// 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";

Lưu ý rằng bạn không cần tính toán chênh lệch nếu bạn sinh ra một cá thể php cho mọi thử nghiệm.

195 hữu ích 5 bình luận chia sẻ

answer

447

Hướng dẫn dùng execution timer trong PHP

Nếu tất cả những gì bạn cần là thời gian đồng hồ treo tường, thay vì thời gian thực hiện CPU, thì thật đơn giản để tính toán:

//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 'Total Execution Time: '.$execution_time.' Mins';
// if you get weird results, use number_format((float) $execution_time, 10) 

Lưu ý rằng điều này sẽ bao gồm thời gian mà PHP đang chờ đợi các tài nguyên bên ngoài như đĩa hoặc cơ sở dữ liệu, vốn không được sử dụng cho max_execut_time.

447 hữu ích 2 bình luận chia sẻ

answer

89

Hướng dẫn dùng execution timer trong PHP

Phiên bản ngắn hơn của câu trả lời của Talal7860

php
// At start of script
$time_start = microtime(true); 

// Anywhere else in the script
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);

Như đã chỉ ra, đây là 'thời gian treo tường' chứ không phải 'thời gian cpu'

89 hữu ích 0 bình luận chia sẻ

answer

68

Hướng dẫn dùng execution timer trong PHP

Cách dễ nhất:

php

$time1 = microtime(true);

//script code
//...

$time2 = microtime(true);
echo 'script execution time: ' . ($time2 - $time1); //value in seconds

68 hữu ích 1 bình luận chia sẻ

answer

31

Hướng dẫn dùng execution timer trong PHP

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";
?>

31 hữu ích 2 bình luận chia sẻ

answer

21

Hướng dẫn dùng execution timer trong PHP

Tôi đã tạo một lớp ExecutTime ngoài câu trả lời phihag mà bạn có thể sử dụng ngoài hộp:

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";
     }
 }

sử dụng:

$executionTime = new ExecutionTime();
$executionTime->start();
// code
$executionTime->end();
echo $executionTime;

Lưu ý: Trong PHP 5, hàm getrusage chỉ hoạt động trong các hệ thống Unix-oid. Kể từ PHP 7, nó cũng hoạt động trên Windows.

21 hữu ích 3 bình luận chia sẻ

answer

11

Hướng dẫn dùng execution timer trong PHP

Gringod tại developerfusion.com đưa ra câu trả lời hay này:

 
php 
   $mtime = microtime(); 
   $mtime = explode(" ",$mtime); 
   $mtime = $mtime[1] + $mtime[0]; 
   $starttime = $mtime; 
;?> 





php 
   $mtime = microtime(); 
   $mtime = explode(" ",$mtime); 
   $mtime = $mtime[1] + $mtime[0]; 
   $endtime = $mtime; 
   $totaltime = ($endtime - $starttime); 
   echo "This page was created in ".$totaltime." seconds"; 
;?>

Từ ( http://www.developerfusion.com/code/2058/determine-execut-time-in-php/ )

11 hữu ích 0 bình luận chia sẻ

answer

8

Hướng dẫn dùng execution timer trong PHP

Cách rẻ nhất và bẩn nhất để làm điều đó chỉ đơn giản là thực hiện microtime()cuộc gọi tại các địa điểm trong mã của bạn mà bạn muốn điểm chuẩn. Thực hiện ngay trước và ngay sau khi truy vấn cơ sở dữ liệu và thật đơn giản để loại bỏ các khoảng thời gian đó khỏi phần còn lại của thời gian thực thi tập lệnh của bạn.

Một gợi ý: thời gian thực thi PHP của bạn hiếm khi sẽ là điều khiến cho kịch bản của bạn hết thời gian chờ. Nếu một kịch bản hết thời gian, nó hầu như sẽ luôn là một cuộc gọi đến một tài nguyên bên ngoài.

Tài liệu microtime PHP: http://us.php.net/microtime

8 hữu ích 0 bình luận chia sẻ

answer

8

Hướng dẫn dùng execution timer trong PHP

Tôi nghĩ bạn nên nhìn vào xdebug. Các tùy chọn định hình sẽ giúp bạn bắt đầu tìm hiểu nhiều mục liên quan đến quá trình.

http://www.xdebug.org/

8 hữu ích 1 bình luận chia sẻ

answer

6

Hướng dẫn dùng execution timer trong PHP

Sẽ đẹp hơn nếu bạn định dạng đầu ra giây như:

echo "Process took ". number_format(microtime(true) - $start, 2). " seconds.";

sẽ in

Process took 6.45 seconds.

Điều này tốt hơn nhiều

Process took 6.4518549156189 seconds.

6 hữu ích 0 bình luận chia sẻ

answer

2

Hướng dẫn dùng execution timer trong PHP

Tôi đã viết một chức năng kiểm tra thời gian thực hiện còn lại.

Cảnh báo: Đếm thời gian thực hiện là khác nhau trên Windows và trên nền tảng 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);
}

Sử dụng:

while (true) {
    // so something

    if (!isRemainingMaxExecutionTimeBiggerThan(5000)) {
        // Time to die.
        // Safely close DB and done the iteration.
    }
}

2 hữu ích 0 bình luận chia sẻ

answer

1

Hướng dẫn dùng execution timer trong PHP

Bạn chỉ có thể muốn biết thời gian thực hiện các phần của tập lệnh của mình. Cách linh hoạt nhất để các bộ phận thời gian hoặc toàn bộ tập lệnh là tạo 3 hàm đơn giản (mã thủ tục được đưa ra ở đây nhưng bạn có thể biến nó thành một lớp bằng cách đặt bộ đếm thời gian lớp {} xung quanh nó và thực hiện một vài điều chỉnh). Mã này hoạt động, chỉ cần sao chép và dán và chạy:

$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');

1 hữu ích 0 bình luận chia sẻ

answer

0

Hướng dẫn dùng execution timer trong PHP

Để thay thế, bạn chỉ có thể đặt dòng này trong các khối mã của mình và kiểm tra nhật ký php, đối với các chức năng thực sự chậm, nó khá hữu ích:

trigger_error("Task done at ". strftime('%H:%m:%S', time()), E_USER_NOTICE); 

Để gỡ lỗi nghiêm trọng, hãy sử dụng XDebug + Cachegrind, xem https://blog.nexcess.net/2011/01/29/diagnose-slow-php-execut-with-xdebug-and-kcachegrind/

0 hữu ích 0 bình luận chia sẻ

answer

0

Hướng dẫn dùng execution timer trong PHP

Mở rộng hơn nữa về câu trả lời của Hamid, tôi đã viết một lớp trợ giúp có thể được bắt đầu và dừng lại nhiều lần (để định hình bên trong một vòng lặp).

   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";
      }
   }

0 hữu ích 0 bình luận chia sẻ

answer

0

Hướng dẫn dùng execution timer trong PHP

Để hiển thị phút và giây bạn có thể sử dụng:

    $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

0 hữu ích 0 bình luận chia sẻ

answer

1

Hướng dẫn dùng execution timer trong PHP

trả lại microtime (đúng) - $ _SERVER ["REQUEST_TIME_FLOAT"];

1 hữu ích 0 bình luận chia sẻ