Skip to content

Instantly share code, notes, and snippets.

@alvaro-canepa
Last active September 24, 2021 10:22
Show Gist options
  • Save alvaro-canepa/31bcad0ef49a9fd524709d181a003113 to your computer and use it in GitHub Desktop.
Save alvaro-canepa/31bcad0ef49a9fd524709d181a003113 to your computer and use it in GitHub Desktop.
PHP Calculate execution time on code
<?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);
}
}
@alvaro-canepa
Copy link
Author

Usage

Measure::start('paginate');
CustomPDF::addPagination($sFilePath, function($sFilePath) {
  $secs = Measure::stop('paginate');
  trace_log(sprintf('Execution time on paginate %s: %s seconds', $sFilePath, $secs));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment