Skip to content

Instantly share code, notes, and snippets.

@itsjavi
Created February 17, 2015 15:34
Show Gist options
  • Select an option

  • Save itsjavi/5b2f1f377ca17ece9293 to your computer and use it in GitHub Desktop.

Select an option

Save itsjavi/5b2f1f377ca17ece9293 to your computer and use it in GitHub Desktop.
A simple "StopWatch" class to measure PHP execution time. The class can handle multiple separate timers at the same time.
<?php
/**
* A simple "StopWatch" class to measure PHP execution time.
* The class can handle multiple separate timers at the same time.
*/
class StopWatch {
/**
* @var $start float The start time of the StopWatch
*/
private static $startTimes = array();
/**
* Start the timer
*
* @param string $timerName string The name of the timer
*
* @return void
*/
public static function start($timerName = 'default') {
self::$startTimes[$timerName] = microtime(true);
}
/**
* Get the elapsed time in seconds
*
* @param string $timerName string The name of the timer to start
*
* @return float The elapsed time since start() was called
*/
public static function elapsed($timerName = 'default') {
return microtime(true) - self::$startTimes[$timerName];
}
/**
* Returns the elapsed time in a meaningful readable message
*
* @param string $timerName
*
* @return string
*/
public static function describe($timerName = 'default') {
return sprintf("StopWatch: '%s' operation completed in %s seconds", $timerName, StopWatch::elapsed($timerName));
}
/**
* Outputs the elapsed time in a meaningful readable message
*
* @param string $timerName
*/
public static function log($timerName = 'default') {
print_r(self::describe($timerName) . "\n");
}
/**
* Removes all timers
*/
public static function flush(){
self::$startTimes = array();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment