Jump to content

Get Memory Usage - Linux


benphelps

Recommended Posts

I wrote this function for a project I'm working on, and I'm am wonder if there is there a better way to do this?  It works, but, its a lot of code and if it can be simplified, I would rather use that.

 

function mem($part){
// get an array of memory info
exec("cat /proc/meminfo", $array);

// break the line title off
$step1 = explode(':', $array[0]);
// drop the " kB"
$step2 = explode(' ', trim($step1[1]));
// set it to a var for later use
$total = $step2[0];

$step4 = explode(':', $array[1]);
$step5 = explode(' ', trim($step4[1]));
$free = $step5[0];

$step7 = explode(':', $array[2]);
$step8 = explode(' ', trim($step7[1]));
$buffer = $step8[0];

$step10 = explode(':', $array[3]);
$step11 = explode(' ', trim($step10[1]));
$cache = $step11[0];

switch($part){
	case "free":
		// add cache+buffers+free to get true free
		$out = (($free+$buffer+$cache)/1024);
	break;
	case "total":
		// the total needs no math
		$out = ($total/1024);
	break;
	case "used":
		// subtract true free from total to get used
		$out = (($total-($free+$buffer+$cache))/1024);
	break;
}
return round($out, 0);
}

//usage
echo mem('free');

Link to comment
https://forums.phpfreaks.com/topic/162444-get-memory-usage-linux/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.