Skip to content

Instantly share code, notes, and snippets.

@chuehnone
Last active June 11, 2019 10:53
Show Gist options
  • Save chuehnone/ccf3599db713068930497e93a583b5fe to your computer and use it in GitHub Desktop.
Save chuehnone/ccf3599db713068930497e93a583b5fe to your computer and use it in GitHub Desktop.
PHP simple debug helper
class DebugHelper
{
/**
* @var int
*/
static $lastTime = 0;
/**
* @var int
*/
static $lastMemory = 0;
/**
* @param string $message
* @param bool $printTime
* @param bool $printMemory
*/
public static function printInfo(string $message, bool $printTime = true, bool $printMemory = true)
{
$currentTime = microtime(true);
$currentMemory = memory_get_usage();
$peakMemory = self::formatMemory(memory_get_peak_usage());
$executedTime = $currentTime - self::$lastTime;
$diffMemory = $currentMemory - self::$lastMemory;
$diffMemory = self::formatMemory($diffMemory);
$totalMemory = self::formatMemory($currentMemory);
if (empty(self::$lastTime)) {
$executedTime = date('Y-m-d H:i:s', $executedTime);
}
echo "{$message} executed time: {$executedTime}, total memory: {$totalMemory}, diff memory: {$diffMemory}, peak memory: {$peakMemory}\n";
self::$lastTime = $currentTime;
self::$lastMemory = $currentMemory;
}
/**
* @param int $memory
*
* @return string
*/
private static function formatMemory(int $memory): string
{
$units = ['bytes', 'KB', 'MB'];
$count = 0;
for (; abs($memory) > 1024 && $count < 2; $memory /= 1024, ++$count);
return sprintf('%.02f %s', $memory, $units[$count]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment