启动和停止计时器 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8310487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start and stop a timer PHP
提问by 125369
I need some information regarding starting and stopping a timer in PHP. I need to measure the elapsed time from the start of my .exe program (I'm using exec()
function in my php script) until it completes the execution and display the time it took in seconds.
我需要一些有关在 PHP 中启动和停止计时器的信息。我需要测量从我的 .exe 程序开始(我exec()
在我的 php 脚本中使用函数)到它完成执行并显示它花费的时间(以秒为单位)所用的时间。
How can I do this?
我怎样才能做到这一点?
回答by Polynomial
You can use microtime
and calculate the difference:
您可以使用microtime
和计算差异:
$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
Here's the PHP docs for microtime
: http://php.net/manual/en/function.microtime.php
这是 PHP 文档microtime
:http: //php.net/manual/en/function.microtime.php
回答by Jon
回答by Anita
For your purpose, this simple class should be all you need:
为了您的目的,这个简单的类应该是您所需要的:
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
回答by vikky
You can use Timer Class
您可以使用计时器类
<?php
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;
}
}
?>
回答by kexplx
Since PHP 7.3 the hrtimefunction should be used for any timing.
自 PHP 7.3 起,hrtime函数可用于任何计时。
$start = hrtime(true);
// execute...
$end = hrtime(true);
echo ($end - $start); // Nanoseconds
echo ($end - $start) / 1000000000; // Seconds
The mentioned microtimefunction relies on the system clock. Which can be modified e.g. by the ntpd program on ubuntu or just the sysadmin.
提到的microtime函数依赖于系统时钟。例如可以通过 ubuntu 上的 ntpd 程序或仅由系统管理员修改。
回答by JalalJaberi
回答by NVRM
As alternative, php has a built-in timer controller: new EvTimer()
.
作为替代方案,php 有一个内置的计时器控制器:new EvTimer()
.
It can be used to make a task scheduler, with proper handling of special cases.
它可用于制作任务调度程序,适当处理特殊情况。
This is not only the Time, but a time transport layer, a chronometer, a lap counter, just as a stopwatch but with php callbacks ;)
这不仅是时间,而且是时间传输层、计时器、计圈器,就像秒表一样,但带有 php 回调 ;)
EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.
The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year, it will still time out after(roughly) one hour.
The callback is guaranteed to be invoked only after its timeout has passed (...). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same prioritywith later time-out values.
The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than onceper event loop iteration.
EvTimer 观察者是简单的相对计时器,它在给定时间后生成事件,并在此后有选择地定期重复。
定时器是基于实时的,也就是说,如果注册一个一小时后超时的事件并将系统时钟重置为去年一月,它仍然会在(大约)一小时后超时。
回调保证仅在其超时过后(...)被调用。如果多个计时器在同一次循环迭代中准备就绪,则具有较早超时值的计时器将在具有较晚超时值的相同优先级的计时器之前被调用。
计时器本身会尽最大努力避免漂移,也就是说,如果计时器配置为每 10 秒触发一次,那么它通常会以恰好 10 秒的间隔触发。但是,如果脚本无法跟上计时器,因为它需要比这 10 秒更长的时间来完成)计时器在每个事件循环迭代中不会触发超过一次。
The first two parameters allows to controls the time delay before execution, and the number of iterations.
前两个参数允许控制执行前的时间延迟和迭代次数。
The third parameter is a callback function, called at each iteration.
第三个参数是一个回调函数,在每次迭代时调用。
after
Configures the timer to trigger after after seconds.
repeat
If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.
https://www.php.net/manual/en/class.evtimer.php
https://www.php.net/manual/en/class.evtimer.php
https://www.php.net/manual/en/evtimer.construct.php
https://www.php.net/manual/en/evtimer.construct.php
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
We can of course easily create this with basic looping and some tempo with sleep()
, usleep()
, or hrtime()
, but new EvTimer()
allows cleans and organized multiples calls, while handling special cases like overlapping.
我们当然可以很容易地与基本的循环和一些节奏与创建此sleep()
,usleep()
或者hrtime()
,但new EvTimer()
允许清洁和有组织的倍数通话,而处理特殊情况下,像重叠。
回答by Luká? K?í?
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"