WP-Mix

A fresh mix of code snippets and tutorials

PHP Get Memory Usage vs. Total

Here is a useful function that I modified for my WordPress plugin, Dashboard Widgets Suite. It returns an array containing the current memory usage and the total memory usage, so you can get and display a ratio of the values as needed.

function shapeSpace_memory_usage() {
	
	$mem_total = memory_get_usage(true);
	$mem_used  = memory_get_usage(false);
	
	$memory = array($mem_total, $mem_used);
	
	foreach ($memory as $key => $value) {
		
		if ($value < 1024) {
			
			$memory[$key] = $value .' B'; 
			
		} elseif ($value < 1048576) {
			
			$memory[$key] = round($value / 1024, 2) .' KB';
			
		} else {
			
			$memory[$key] = round($value / 1048576, 2) .' MB';
			
		}
		
	}
	
	return $memory;
	
}

This function returns an array with both values, memory used and total memory. Here is an example of usage:

list($mem_total, $mem_used) = shapeSpace_memory_usage();
echo $mem_total . ' / ' . $mem_used;

..which outputs something like:

3.25 MB / 2.9 MB

Kaboom.

★ Pro Tip:

USP ProSAC Pro