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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.