Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Last active April 6, 2022 08:23
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 nasrulhazim/4c0e18a0fb03046ba64b73bc25771c88 to your computer and use it in GitHub Desktop.
Save nasrulhazim/4c0e18a0fb03046ba64b73bc25771c88 to your computer and use it in GitHub Desktop.
Get Memory Utilisation
<?php
namespace App\Actions;
class MemoryUtilisation
{
public $units = ['B','KB','MB','GB','TB','PB'];
public $start;
public $startTime;
public $end;
public $endTime;
public function start()
{
$this->start = memory_get_usage();
$this->startTime = date('Y-m-d H:i:s');
return $this;
}
public function end()
{
$this->end = memory_get_usage();
$this->endTime = date('Y-m-d H:i:s');
return $this;
}
public function toArray()
{
return [
'start' => $this->toHuman($this->start),
'start_time' => $this->startTime,
'end' => $this->toHuman($this->end),
'end_time' => $this->endTime,
'total' => $this->toHuman($this->end - $this->start)
];
}
private function toHuman($value)
{
return @round(
$value /
pow(
1024,
($i = floor(log($value, 1024)))
), 2).' '.$this->units[$i];
}
}
$mem = new \App\Actions\MemoryUtilisation();
$mem->start();
// do your stuff...
echo 'blablablabla';
echo 'do something else';
$mem->end();
// get status
$mem->toArray()
@nasrulhazim
Copy link
Author

Output:

  [
     "start" => "33.26 MB",
     "start_time" => "2022-04-06 14:29:20",
     "end" => "33.28 MB",
     "end_time" => "2022-04-06 14:29:34",
     "total" => "24.91 KB",
  ]

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