Skip to content

Instantly share code, notes, and snippets.

@leMaur
Created June 28, 2018 10:18
Show Gist options
  • Save leMaur/b6a04879f369b7d0e9f0508a34ed6197 to your computer and use it in GitHub Desktop.
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.
<?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
);
}
}
@leMaur
Copy link
Author

leMaur commented Jun 28, 2018

How to use it

In your Command, import the Benchmarkable trait. Here an example:

<?php

namespace App\Console\Commands;

use App\Console\Benchmarkable;

class AmazingCommand extends Command
{
    use Benchmarkable;

    ...
}

then in your methods:

public function handle()
{
    $this->setBenchmark('mark_1');

    ...

    $this->line("Completed in " . $this->benchmarkFrom('mark_1'));
}

and the output will be:

$ php artisan amazing:command
Completed in 1.0746 sec.

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