Hướng dẫn dùng start stopwatch trong PHP

answer

195

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

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

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

answer

21

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

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

 
 





Từ [ //www.developerfusion.com/code/2058/determine-execut-time-in-php/ ]

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

answer

8

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: //us.php.net/microtime

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

answer

8

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.

//www.xdebug.org/

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

answer

6

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

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

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['//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

Để 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 //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

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

Để 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

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

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

Chủ Đề