Skip to content

Instantly share code, notes, and snippets.

@jpcaparas
Last active August 24, 2020 03:37
Show Gist options
  • Save jpcaparas/1453767e73be4e294b5732ac68b64d52 to your computer and use it in GitHub Desktop.
Save jpcaparas/1453767e73be4e294b5732ac68b64d52 to your computer and use it in GitHub Desktop.
Dumps or logs performance in Laravel
<?php
/**
* Dumps or logs performance of code.
*/
class BenchmarksPerformance
{
private static $startTime;
private static $startLine;
private static $endLine;
public static function startBenchmark(): void
{
$bt = debug_backtrace();
$caller = array_shift($bt);
self::$startLine = $caller['line'];
$r = explode(' ', microtime());
$r = $r[1] + $r[0];
self::$startTime = $r;
}
public static function endBenchMark(bool $logInstead = false): void
{
if (!self::$startTime) {
throw new \LogicException('startBenchmark() needs to be called before running endBenchmark()');
}
$bt = debug_backtrace();
$caller = array_shift($bt);
self::$endLine = $caller['line'];
$r = explode(' ', microtime());
$r = $r[1] + $r[0];
$difference = round($r - self::$startTime, 4);
$message = basename($caller['file']) . ' [lines ' . self::$startLine . ':' . self::$endLine . ']' . ' took ' . $difference . ' seconds to run.';
// Reset startTime and startLine
self::$startLine = null;
self::$startTime = null;
if ($logInstead) {
logger($message);
return;
}
dump($message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment