Timer - PHP

php

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';



Projects

Site

Social

Tags