Last active
August 24, 2020 03:37
-
-
Save jpcaparas/1453767e73be4e294b5732ac68b64d52 to your computer and use it in GitHub Desktop.
Dumps or logs performance in Laravel
This file contains 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 | |
/** | |
* 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