找出PHP脚本何时开始执行

时间:2014-03-01 18:39:05

标签: php oop debugging

如果要计算特定PHP脚本运行的时间,请执行以下操作:

//Remember beginning time of the script
define("START_TIME", time());

//Do some loop or whatever
   ...

//At the end, calculate the difference of start and current time
echo "This script has been running for ".(time() - START_TIME)."\n";

嗯,这一切都很好,但是想象一下你正在创建一个类/库,它可能会包含在稍后的脚本中,并且还需要计算运行时。

PHP中是否有一个函数可以在脚本启动时给我时间戳 - 或者是一个允许我扣除它的函数?
这就是我需要的:

class Blah {
    public getRuntime() {
        static $startTime = get_start_time_magic_function();
        return time() - $startTime;
    }
}

我要求的理由是,我在一个类中有一个“无限”循环,它应该在执行限制生效时自动结束。如果脚本被PHP杀死,那将对处理的数据造成损害。

2 个答案:

答案 0 :(得分:0)

引自http://php.net/manual/en/function.microtime.php(示例#3):

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

答案 1 :(得分:-1)

define("START_TIME", time());
define("MAX_DURATION", 3);
while (true) {
    $current_duration = time() - START_TIME;

    // do your stuff here

    if($current_duration >= MAX_DURATION) {
        echo "This script has been running for ". $current_duration ." seconds \n";
        break;
    }
}