Timer.php (2373B)
1 <?php 2 /* 3 * This file is part of the PHP_Timer package. 4 * 5 * (c) Sebastian Bergmann <sebastian@phpunit.de> 6 * 7 * For the full copyright and license information, please view the LICENSE 8 * file that was distributed with this source code. 9 */ 10 11 /** 12 * Utility class for timing. 13 * 14 * @since Class available since Release 1.0.0 15 */ 16 class PHP_Timer 17 { 18 /** 19 * @var array 20 */ 21 private static $times = array( 22 'hour' => 3600000, 23 'minute' => 60000, 24 'second' => 1000 25 ); 26 27 /** 28 * @var array 29 */ 30 private static $startTimes = array(); 31 32 /** 33 * @var float 34 */ 35 public static $requestTime; 36 37 /** 38 * Starts the timer. 39 */ 40 public static function start() 41 { 42 array_push(self::$startTimes, microtime(true)); 43 } 44 45 /** 46 * Stops the timer and returns the elapsed time. 47 * 48 * @return float 49 */ 50 public static function stop() 51 { 52 return microtime(true) - array_pop(self::$startTimes); 53 } 54 55 /** 56 * Formats the elapsed time as a string. 57 * 58 * @param float $time 59 * @return string 60 */ 61 public static function secondsToTimeString($time) 62 { 63 $ms = round($time * 1000); 64 65 foreach (self::$times as $unit => $value) { 66 if ($ms >= $value) { 67 $time = floor($ms / $value * 100.0) / 100.0; 68 69 return $time . ' ' . ($time == 1 ? $unit : $unit . 's'); 70 } 71 } 72 73 return $ms . ' ms'; 74 } 75 76 /** 77 * Formats the elapsed time since the start of the request as a string. 78 * 79 * @return string 80 */ 81 public static function timeSinceStartOfRequest() 82 { 83 return self::secondsToTimeString(microtime(true) - self::$requestTime); 84 } 85 86 /** 87 * Returns the resources (time, memory) of the request as a string. 88 * 89 * @return string 90 */ 91 public static function resourceUsage() 92 { 93 return sprintf( 94 'Time: %s, Memory: %4.2fMb', 95 self::timeSinceStartOfRequest(), 96 memory_get_peak_usage(true) / 1048576 97 ); 98 } 99 } 100 101 if (isset($_SERVER['REQUEST_TIME_FLOAT'])) { 102 PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME_FLOAT']; 103 } elseif (isset($_SERVER['REQUEST_TIME'])) { 104 PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME']; 105 } else { 106 PHP_Timer::$requestTime = microtime(true); 107 }