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
<?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];
}
}
Basic usage:
$this->statsTimerStart()
.. do stuff ..
log 'stuff processed in ' . $this->statsTimerRuntime() . ' using ' . $this->statsMemoryUsed();