Calculate Memory used by a PHP

Share this on facebook

How to measure the memory consumed by a single php page ? A Simple question by a more simple solution.Calculating memory used in php is very simple , all you need to do is to put this code in the starting and ending of the php page you want to measure the memory used.

memory_get_usage(); – A Function which returns the current memory consumed by current request.

Paste the above function at the immediate starting of the php page after <?php tag and again at the end of the page . Due to this you will be able to see the memory consumed before page started executing and the memory consumed by php page / script after the execution.

Demo : Consider a simple wordpress blog. The default index page , default theme and no one post blog shows following consumption result.

 

In the screenshot you can see the page consumption in the beginning and at the end of the wordpress which shows the memory consumed before and after the execution of page , the memory consumed. A default installation consumes 13MB! Similary other CMS / Scripts might be consuming more or less memory depending upon the code. Further for better debugging , you can use the code anywhere in the code (thats obvious i guess!).

 

This method can be used on  any php page without any problems. However the result may be displayed in Byte form to convert it to proper display , use the following code

FOR DISPLAYING Memory used in Kb/MB/GB used :

function convert($size)
{
$unit=array(‘b’,'kb’,'mb’,'gb’,'tb’,'pb’);
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).’ ‘.$unit[$i];
}

echo convert(memory_get_usage(true)); // Used this line wherever you want to display the memory used!

Comments / suggestions always welcomed!

 

About the author — Kevin Shah


Tags: , , , ,