Отслеживание времени выполнения скрипта в PHP

230

PHP должен отслеживать количество процессорного времени, которое определенный script использовал для обеспечения максимального предела max_execution_time.

Есть ли способ получить доступ к этому внутри script? Я хотел бы включить некоторые записи с моими испытаниями о том, сколько CPU было сгорело в реальном PHP (время не увеличивается, когда script сидит и ждет базы данных).

Я использую ящик Linux.

Теги:
performance

16 ответов

194
Лучший ответ

На Unixoid системах (и в php 7+ на Windows также) вы можете использовать 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 для каждого теста.

  • 0
    Должно ли значение в конце вычитаться из значения в начале скрипта? Я получаю действительно странные цифры, если не получу. Например, страница, на создание которой ушло 0,05 секунды, говорит, что процессору потребовалось 6 секунд ... это правильно? Смотрите здесь: blog.rompe.org/node/85
  • 0
    @Darryl Hein: О, и вы получите странные результаты, потому что вы используете конкатенацию строк вместо сложения;)
Показать ещё 4 комментария
449

Если все, что вам нужно, это время настенных часов, а не время выполнения ЦП, то это легко рассчитать:

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

  • 35
    Привет - это отслеживает «время настенных часов», а не время процессора.
  • 13
    Отлично, я искал решение для отслеживания времени на стене.
85

Более короткая версия ответа 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);

Как указывалось, это "время настенного времени", а не "время процессора"

66

Самый простой способ:

<?php

$time1 = microtime(true);

//script code
//...

$time2 = microtime(true);
echo 'script execution time: ' . ($time2 - $time1); //value in seconds
  • 4
    чем это отличается от ответа talal7860 ...?
27
<?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";
?>
  • 0
    Я не получил результат в считанные секунды
  • 0
    Вы должны использовать PHP 5.4.0
20

Я создал класс ExecutionTime из ответа phihag, который вы можете использовать из коробки:

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.

  • 2
    Примечание. В Windows getrusage работает только с PHP 7.
  • 0
    @MartinvanDriel Я добавил примечание. Спасибо
Показать ещё 1 комментарий
11

Gringod на developerfusion.com дает хороший ответ:

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

8

Я думаю, вам стоит посмотреть на xdebug. Параметры профилирования дадут вам возможность начать изучение многих связанных с процессом элементов.

http://www.xdebug.org/

  • 1
    Просто убедитесь, что вы не устанавливаете xdebug на рабочий сервер с большим количеством веб-сайтов. Он производит огромное количество журналов и может перегружать небольшой SSD-накопитель.
7

Самый дешевый и самый грязный способ сделать это - просто позвонить microtime() в местах вашего кода, который вы хотите сравнить. Сделайте это прямо перед и сразу после запросов к базе данных, и просто удалить эти длительности из оставшейся части вашего времени script.

Подсказка: ваше время выполнения PHP редко будет тем, что делает ваш тайм-аут script. Если время ожидания script почти всегда будет вызовом внешнего ресурса.

PHP microtime-документация: http://us.php.net/microtime

6

Это будет красивее, если вы отформатируете выходные секунды следующим образом:

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

напечатает

Process took 6.45 seconds.

Это намного лучше, чем

Process took 6.4518549156189 seconds.
5
<?php
    $time1 = microtime(true);
       //script code
       //...for or if or any thing you want to know!
    $time2 = microtime(true);
    echo 'Total execution time: ' . ($time2 - $time1);//value in seconds
?>
1

Я написал функцию, которая проверяет оставшееся время выполнения.

Предупреждение: Счет времени выполнения отличается в 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.
    }
}
1

Вам может потребоваться узнать время выполнения частей вашего script. Самый гибкий способ создания временных частей или всего script состоит в создании 3 простых функций (здесь приведено процедурный код, но вы можете превратить его в класс, добавив вокруг него класс timer {} и сделав пару настроек). Этот код работает, просто скопируйте и вставьте и запустите:

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

Для отображения минут и секунд вы можете использовать:

    $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

Более подробно остановившись на ответе Хамида, я написал вспомогательный класс, который можно многократно запускать и останавливать (для профилирования внутри цикла).

   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

В качестве альтернативы вы можете просто поместить эту строку в свои блоки кода и проверить журналы 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/

Ещё вопросы

Сообщество Overcoder
Наверх
Меню