启动和停止计时器PHP
我需要一些有关在PHP中启动和停止计时器的信息。 我需要测量从启动我的.exe程序(我在PHP脚本中使用exec()函数)到完成执行并显示所花费的时间(以秒为单位)之后经过的时间。有没有办法我可以做到这一点。
谢谢
125369 asked 2020-07-23T23:57:28Z
5个解决方案
102 votes
您可以使用microtime并计算差异:
$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
这是microtime的PHP文档:[http://php.net/manual/en/function.microtime.php]
Polynomial answered 2020-07-23T23:57:47Z
7 votes
使用microtime功能。 该文档包含示例代码。
Jon answered 2020-07-23T23:58:07Z
6 votes
为了您的目的,这个简单的类应该是您所需要的:
class Timer {
private $time = null;
public function __construct() {
$this->time = time();
echo 'Working - please wait..
';
}
public function __destruct() {
echo '
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
Anita answered 2020-07-23T23:58:27Z
3 votes
您可以使用计时器类
class Timer {
var $classname = "Timer";
var $start = 0;
var $stop = 0;
var $elapsed = 0;
# Constructor
function Timer( $start = true ) {
if ( $start )
$this->start();
}
# Start counting time
function start() {
$this->start = $this->_gettime();
}
# Stop counting time
function stop() {
$this->stop = $this->_gettime();
$this->elapsed = $this->_compute();
}
# Get Elapsed Time
function elapsed() {
if ( !$elapsed )
$this->stop();
return $this->elapsed;
}
# Resets Timer so it can be used again
function reset() {
$this->start = 0;
$this->stop = 0;
$this->elapsed = 0;
}
#### PRIVATE METHODS ####
# Get Current Time
function _gettime() {
$mtime = microtime();
$mtime = explode( " ", $mtime );
return $mtime[1] + $mtime[0];
}
# Compute elapsed time
function _compute() {
return $this->stop - $this->start;
}
}
?>
vikky answered 2020-07-23T23:58:46Z
0 votes
class Timer
{
private $startTime = null;
public function __construct($showSeconds = true)
{
$this->startTime = microtime(true);
echo 'Working - please wait...' . PHP_EOL;
}
public function __destruct()
{
$endTime = microtime(true);
$time = $endTime - $this->startTime;
$hours = (int)($time / 60 / 60);
$minutes = (int)($time / 60) - $hours * 60;
$seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
$timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
echo 'Job finished in ' . $timeShow . PHP_EOL;
}
}
$t = new Timer(); // echoes "Working, please wait.."
[some operations]
unset($t); // echoes "Job finished in h:m:s"
Lukáš Kříž answered 2020-07-23T23:59:02Z