Skip to content

Instantly share code, notes, and snippets.

@navarr
Last active August 29, 2015 14:13
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 navarr/ff47851ef03fbb6b3a15 to your computer and use it in GitHub Desktop.
Save navarr/ff47851ef03fbb6b3a15 to your computer and use it in GitHub Desktop.
N98 Magerun MemoryCommand
<?php
namespace Briteskies\Commands;
use N98\Magento\command\AbstractMagentoCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class MemoryCommand extends AbstractMagentoCommand
{
protected function configure()
{
$this->setName('briteskies:memory')->setDescription('Determine amount of memory on the host');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$memory = $this->getMemory();
$output->writeln("Total Memory: " . $this->memoryFormat($memory->total));
$output->writeln("Free Memory: " . $this->memoryFormat($memory->free));
}
/**
* @return \StdClass
*/
private function getMemory()
{
$memory = new \StdClass();
$memInfo = explode("\n", file_get_contents('/proc/meminfo'));
$totalRaw = preg_grep('/MemTotal/', $memInfo);
$freeRaw = preg_grep('/MemFree/', $memInfo);
$memory->total = $this->getBytesFromMemoryString(array_pop($totalRaw));
$memory->free = $this->getBytesFromMemoryString(array_pop($freeRaw));
return $memory;
}
/**
* @param $string
* @return int
*/
private function getBytesFromMemoryString($string)
{
// Split up the label and value
$ra = explode(":", $string);
// Remove tabs & whitespace
$value = trim($ra[1]);
// Remove the kB & whitespace (strips 2 characters from the end then trims whitespace)
$value = trim(substr($value, 0, -2));
// Convert to a number and multiply by 1024 to get bytes from kibibytes
$bytes = intval($value, 10) * 1024;
return $bytes;
}
/**
* @param int $bytes
* @return string
*/
private function memoryFormat($bytes)
{
$magnitudes = array('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
reset($magnitudes);
$magnitude = "B";
$amt = $bytes;
while ($amt > 1024) {
$amt = $amt / 1024;
$magnitude = current($magnitudes);
if (!next($magnitudes)) {
break;
}
}
return number_format($amt, 2) . " " . $magnitude;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment