Last active
January 3, 2016 04:29
-
-
Save craiga/8409711 to your computer and use it in GitHub Desktop.
Functions for timing.
This file contains 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 | |
/** | |
* Functions for timing. Requires {@link https://gist.github.com/craiga/1849563 Logging} and {@link https://gist.github.com/craiga/3186287 formatTime}. | |
* | |
* @author Craig Anderson <craiga@craiga.id.au> | |
* @link https://gist.github.com/craiga/8409711 | |
*/ | |
trait Timable { | |
use Logging; // https://gist.github.com/craiga/1849563 | |
protected $_timers = array(); | |
protected function _startTimer($timerName) { | |
if(isset($this->_timers[$timerName])) { | |
throw new RuntimeException(sprintf("A timer named %s already exists", $timerName)); | |
} | |
$this->_timers[$timerName] = microtime(true); | |
} | |
protected function _endTimer($timerName = null) { | |
if(is_null($timerName)) { | |
$timerNames = array_keys($this->_timers); | |
$timerName = $timerNames[count($timerNames) - 1]; | |
} | |
if(!isset($this->_timers[$timerName])) { | |
throw new RuntimeException(sprintf("A timer named %s doesn't exist", $timerName)); | |
} | |
$startTime = $this->_timers[$timerName]; | |
$endTime = microtime(true); | |
unset($this->_timers[$timerName]); | |
$this->_log("Timer %s ran for %s", | |
$timerName, | |
formatTime($endTime - $startTime) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment