Skip to content

Instantly share code, notes, and snippets.

@mbrowniebytes
Created January 7, 2021 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrowniebytes/7b20812689226816ce8887da24f233e0 to your computer and use it in GitHub Desktop.
Save mbrowniebytes/7b20812689226816ce8887da24f233e0 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
trait Stats
{
private $timer_start;
private $timer_finish;
public function statsTimerStart()
{
$this->timer_start = microtime(true);
}
public function statsTimerFinish()
{
$this->timer_finish = microtime(true);
}
public function statsTimerRuntime()
{
if (empty($this->timer_finish)) {
$this->statsTimerFinish();
}
$runtime = $this->timer_finish - $this->timer_start;
return gmdate('H:i:s', $runtime);
}
public function statsMemoryUsed()
{
$memory_used = memory_get_peak_usage(true);
return $this->statsFormatBytes($memory_used);
}
public function statsFormatBytes(int $bytes, int $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$unit_index = 0;
while ($bytes > 1024) {
$bytes /= 1024;
$unit_index++;
}
return round($bytes, $precision) . $units[$unit_index];
}
}
@mbrowniebytes
Copy link
Author

Sometimes you want to know how long a script took and how much memory it consumed.

Run Time and Memory used can also be useful if tracked overtime, for example in:

  • cron/cli scripts
  • web requests
  • api requests

While tools such as New Relic (paid), DataDog (paid), NetData (opensource), Prometheus (opensource) could be used, sometimes a simpler local solution is all that is needed.

Here is a simple Trait to extend your classes with

@mbrowniebytes
Copy link
Author

Basic usage:

$this->statsTimerStart()
.. do stuff ..
log 'stuff processed in ' . $this->statsTimerRuntime() . ' using ' . $this->statsMemoryUsed();

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