Last active
August 29, 2015 14:10
-
-
Save thomascrepain/f9bf832dac7545f8116b to your computer and use it in GitHub Desktop.
Timer class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class Timer | |
*/ | |
class Timer | |
{ | |
/** | |
* @var float|null | |
*/ | |
protected $startTime; | |
/** | |
* @var float|null | |
*/ | |
protected $endTime; | |
public function __construct($start = false) | |
{ | |
if ($start) { | |
$this->start(); | |
} | |
} | |
public function start() | |
{ | |
$this->startTime = $this->getCurrentTime(); | |
} | |
public function stop() | |
{ | |
$this->endTime = $this->getCurrentTime(); | |
} | |
public function reset() | |
{ | |
$this->startTime = null; | |
$this->endTime = null; | |
} | |
public function getCurrentTime() | |
{ | |
return microtime(true); | |
} | |
public function getElapsedTime($unit = 's') | |
{ | |
$startTime = is_null($this->startTime) ? $this->getCurrentTime() : $this->getStartTime(); | |
$endTime = $this->isTimerRunning() ? $this->getCurrentTime() : $this->getEndTime(); | |
return ($endTime - $startTime) * $this->getMultiplicationFactorForUnit($unit); | |
} | |
/** | |
* @return float | |
*/ | |
public function getStartTime() | |
{ | |
return $this->startTime; | |
} | |
/** | |
* @return float | |
*/ | |
public function getEndTime() | |
{ | |
return $this->endTime; | |
} | |
/** | |
* @param $unit | |
* @return float|int | |
*/ | |
protected function getMultiplicationFactorForUnit($unit) | |
{ | |
$multiplicationFactor = 1; | |
switch ($unit) { | |
// milliseconds | |
case 'ms': | |
$multiplicationFactor = 1000; | |
break; | |
// seconds | |
case 's': | |
$multiplicationFactor = 1; | |
break; | |
// minutes | |
case 'm': | |
$multiplicationFactor = 1 / 60; | |
break; | |
} | |
return $multiplicationFactor; | |
} | |
protected function isTimerRunning() | |
{ | |
return is_null($this->endTime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment