Skip to content

Instantly share code, notes, and snippets.

@craiga
Last active January 3, 2016 04:29
Show Gist options
  • Save craiga/8409711 to your computer and use it in GitHub Desktop.
Save craiga/8409711 to your computer and use it in GitHub Desktop.
Functions for timing.
<?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