Last active
September 24, 2021 10:22
-
-
Save alvaro-canepa/31bcad0ef49a9fd524709d181a003113 to your computer and use it in GitHub Desktop.
PHP Calculate execution time on code
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 Measure | |
{ | |
/** @var array */ | |
protected static $timers; | |
/** | |
* Sets initial timer for specified name (optional) | |
* | |
* @param string $sName | |
*/ | |
public static function start(string $sName = 'defaults'): void | |
{ | |
if (!self::$timers) { | |
self::$timers = []; | |
} | |
self::$timers[$sName] = self::mt(); | |
} | |
/** | |
* Get elapsed time after start in seconds | |
* Returns -1 in case of no current time started with name $sName | |
* | |
* @param string $sName | |
* | |
* @return float|int | |
*/ | |
public static function elapsed(string $sName = 'defaults') | |
{ | |
$fStart = self::get($sName); | |
if ($fStart == -1) { | |
return $fStart; | |
} | |
$fEnd = self::mt(); | |
return $fEnd - $fStart; | |
} | |
/** | |
* Get end time in seconds | |
* Returns -1 in case of no current time started with name $sName | |
* | |
* @param string $sName | |
* | |
* @return float|int | |
*/ | |
public static function stop(string $sName = 'defaults') | |
{ | |
$fEnd = self::elapsed($sName); | |
if ($fEnd != -1) { | |
unset(self::$timers[$sName]); | |
} | |
return $fEnd; | |
} | |
/** | |
* Get initial timer for specified name | |
* Returns -1 in case of no current time started with name $sName | |
* | |
* @param string $sName | |
* | |
* @return float|int | |
*/ | |
public static function get(string $sName = 'defaults') | |
{ | |
if (!self::$timers || !array_key_exists($sName, self::$timers)) { | |
return -1; | |
} | |
return self::$timers[$sName]; | |
} | |
/** | |
* Return current Unix timestamp with microseconds | |
* @return float | |
*/ | |
public static function mt(): float | |
{ | |
return microtime(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage