Created
June 28, 2018 10:18
-
-
Save leMaur/b6a04879f369b7d0e9f0508a34ed6197 to your computer and use it in GitHub Desktop.
Save `Benchmarkable.php` in `app/Console`. Then use it in your Artisan Commands.
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 | |
namespace App\Console; | |
/** | |
* Benchmark functionality for Artisan Command. | |
* | |
* @author Maurizio Lepora <[email protected]> | |
* @license MIT | |
*/ | |
trait Benchmarkable | |
{ | |
/** | |
* Store the benchmarks. | |
* | |
* @var \Illuminate\Support\Collection | |
*/ | |
protected $benchmarks; | |
/** | |
* Set a new unique mark. | |
* | |
* @param string $name The unique key name. | |
*/ | |
protected function setBenchmark(string $name): self | |
{ | |
if (! $this->benchmarks) { | |
$this->benchmarks = collect([]); | |
} | |
if ($this->benchmarks->keys()->contains($name)) { | |
throw new Exception("The key `{$name}` already exists."); | |
} | |
$this->benchmarks->put($name, microtime(true)); | |
return $this; | |
} | |
/** | |
* Calculates the elapsed time from the given mark. | |
* | |
* @param string $name The unique key name. | |
* @param int $decimals = 3 The number of decimals to output. | |
* @param string $suffix = 'sec.' The text to show after the elapsed time. | |
* @return string The elapsed time formatted. | |
*/ | |
protected function benckmarkFrom(string $name, int $decimals = 3, string $suffix = 'sec.'): string | |
{ | |
return trim( | |
number_format( | |
microtime(true) - $this->benchmarks->get($name), | |
$decimals | |
) . ' ' . $suffix | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use it
In your
Command
, import theBenchmarkable
trait. Here an example:then in your methods:
and the output will be: