Timer - PHP
php
on July 5, 2012
A small timer class I wrote:
Timer.php
<?php
class Timer {
ใใใใconst MICROSECONDS = 0;
ใใใใconst SECONDS = 1;
ใใใใprivate $startTime;
ใใใใprivate $interval = 0;
ใใใใprivate $units;
ใใใใ
ใใใใpublic function __construct($units = Timer::MICROSECONDS) {
ใใใใใใใใ$this->startTime = $this->timeAsMilliseconds();
ใใใใใใใใ$this->units = $units;
ใใใใ}
ใใใใpublic function start() {
ใใใใใใใใ$this->startTime = $this->timeAsMilliseconds();
ใใใใ}
ใใใใpublic function restart() {
ใใใใใใใใ$this->start();
ใใใใ}
ใใใใpublic function elapsedTime() {
ใใใใใใใใ$diff = $this->timeAsMilliseconds() - $this->startTime;
ใใใใใใใใif($this->units == Timer::MICROSECONDS) {
ใใใใใใใใใใใใreturn $diff;
ใใใใใใใใ} else {
ใใใใใใใใใใใใreturn (int)($diff / 1000);
ใใใใใใใใ}
ใใใใ}
ใใใใpublic function setInterval($interval) {
ใใใใใใใใif($this->units == Timer::SECONDS) {
ใใใใใใใใใใใใ$interval *= 1000;
ใใใใใใใใ}
ใใใใใใใใ$this->interval = $interval;
ใใใใ}
ใใใใpublic function intervalElapsed() {
ใใใใใใใใreturn ($this->timeAsMilliseconds() - $this->startTime) > $this->interval;
ใใใใ}
ใใใใprivate function timeAsMilliseconds() {
ใใใใใใใใreturn round(microtime(true) * 1000);
ใใใใ}
ใใใใ
}
TimerDemo.php
require_once('Timer.php');
// timer test, milliseconds
$timer = new Timer();
$timer->start();
usleep(1000);
echo $timer->elapsedTime() . 'ms';
// timer test, seconds
$timer = new Timer(Timer::SECONDS);
$timer->start();
usleep(1000);
echo $timer->elapsedTime() . 's';
// interval test, milliseconds
$timer = new Timer();
$timer->setInterval(2000);
$timer->start();
usleep(1000);
echo $timer->intervalElapsed() ? 'true' : 'false';
usleep(1200);
echo $timer->intervalElapsed() ? 'true' : 'false';
// interval test, seconds
$timer = new Timer(Timer::SECONDS);
$timer->setInterval(2);
$timer->start();
usleep(1000);
echo $timer->intervalElapsed() ? 'true' : 'false';
usleep(1200);
echo $timer->intervalElapsed() ? 'true' : 'false';