PHP代码执行时间

时间:2010-05-31 08:49:24

标签: php

如何查找我的代码执行时间?

我正在使用以下代码段。

我对此不满意?

list ($msec, $sec) = explode(' ', microtime());
$microtime = (float)$msec + (float)$sec;

9 个答案:

答案 0 :(得分:21)

我为此创建了这个简单的类:

class timer
{
    private $start_time = NULL;
    private $end_time = NULL;

    private function getmicrotime()
    {
      list($usec, $sec) = explode(" ", microtime());
      return ((float)$usec + (float)$sec);
    }

    function start()
    {
      $this->start_time = $this->getmicrotime();
    }

    function stop()
    {
      $this->end_time = $this->getmicrotime();
    }

    function result()
    {
        if (is_null($this->start_time))
        {
            exit('Timer: start method not called !');
            return false;
        }
        else if (is_null($this->end_time))
        {
            exit('Timer: stop method not called !');
            return false;
        }

        return round(($this->end_time - $this->start_time), 4);
    }

    # an alias of result function
    function time()
    {
        $this->result();
    }

}

对于时间脚本,您可以使用它:

$timer = new timer();

$timer->start();
// your code now
$timer->stop();

// show result now
echo $timer->result();

答案 1 :(得分:9)

我正在使用以下课程确定已过去的时间:

class StopWatch {
    private static $total;

    public static function start() {
        self::$total = microtime(true);
    }

    public static function elapsed() {
        return microtime(true) - self::$total;
    }
}

您只需要在开始时StopWatch::startStopWatch::elapsed,只要您想知道从一开始就经过了多长时间。

答案 2 :(得分:5)

您可以使用parameter of microtime

$microtime = microtime(true);

答案 3 :(得分:3)

如果要对脚本进行概要分析,请使用XDebug + {K,Win} Cachegrind,这些是免费工具,可提供代码执行的可视化映射。

答案 4 :(得分:2)

如果您想要实际的处理器时序:

$rUsage = getrusage();
echo 'User time = '.sprintf('%.4f',($rUsage['ru_utime.tv_sec'] * 1e6 + $rUsage['ru_utime.tv_usec']) / 1e6).' seconds';
echo 'system time = '.sprintf('%.4f',($rUsage['ru_stime.tv_sec'] * 1e6 + $rUsage['ru_stime.tv_usec']) / 1e6).' seconds';

答案 5 :(得分:1)

在LINUX中:

对于一个简单的代码:

time php -r "echo 'hello';"

输出:

您好
真实0m0.095s
用户0m0.033s
sys 0m0.055s

对于php文件:

time php hello.php

输出:

您好
真正的0m0.073s
用户0m0.025s
sys 0m0.047s

答案 6 :(得分:0)

如果运行Unix,请查看time command

答案 7 :(得分:0)

感谢您分享您的信息。

下面的一个也很接近我的解决方案。

function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

SOURCE CODE

$time_end = microtime_float();
$time = round($time_end - $time_start, 4);

echo "Last uncached content render took $time seconds";

答案 8 :(得分:0)

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