启动和停止计时器PHP

125*_*369 44 php timer

我需要一些关于在PHP中启动和停止计时器的信息.我需要测量从启动我的.exe程序(我在我的php脚本中使用exec()函数)开始经过的时间,直到它完成执行并显示它花费的时间(以秒为单位).有没有办法如何做到这一点.

谢谢

Pol*_*ial 103

您可以使用microtime并计算差异:

$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
Run Code Online (Sandbox Code Playgroud)

以下是PHP文档microtime:http://php.net/manual/en/function.microtime.php


Jon*_*Jon 7

使用该microtime功能.该文档包括示例代码.


yoo*_*ooy 7

自 PHP 7.3 起,应使用hrtime函数进行检测。

$start = hrtime(true);
// run your code...
$end = hrtime(true);   

echo ($end - $start);                // Nanoseconds
echo ($end - $start) / 1000000;      // Milliseconds
echo ($end - $start) / 1000000000;   // Seconds
Run Code Online (Sandbox Code Playgroud)

提到的microtime函数依赖于系统时钟。例如可以通过 ubuntu 上的 ntpd 程序或仅由系统管理员修改。


小智 6

为了您的目的,这个简单的课程应该是您所需要的:

class Timer {
    private $time = null;
    public function __construct() {
        $this->time = time();
        echo 'Working - please wait..<br/>';
    }

    public function __destruct() {
        echo '<br/>Job finished in '.(time()-$this->time).' seconds.';
    }
}


$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in n seconds." n = seconds elapsed
Run Code Online (Sandbox Code Playgroud)