Created
January 7, 2021 20:34
-
-
Save mbrowniebytes/7b20812689226816ce8887da24f233e0 to your computer and use it in GitHub Desktop.
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 | |
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();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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