Last updated on February 22nd, 2022 at 01:19 pm

PHP has a built in function memory_get_peak_usage() which help us to find the memory usage by a single php script in bytes. This function returns the peak of memory, in bytes, that’s been allocated to the php script.

Here we are providing you a simple php function that help web developers to find the memory usage in Bytes, Kilo Bytes[KB] and Mega Bytes[MB] of their own scripts.

<?php
function get_memory_used($val)
{
$mem_usage = memory_get_peak_usage(false);
if ($mem_usage < 1024)
echo $mem_usage." Bytes";
elseif ($mem_usage < 1048576)
echo "Memory used $val ".round($mem_usage/1024,2)." KB";
else echo "Memory used $val ".round($mem_usage/1048576,2)." MB";
echo "<br/>";
 }
get_memory_used("before");
//You Can Put Your Own Script Here To Test The Memory Usage
$myvar = str_repeat("TESTLOAD", 200000);
get_memory_used("after");
//Unset all the variables declared here
unset($myvar);
$myvar=null;
var_dump($myvar);
?>

The script basically give you an idea how much memory is being used before and after a php code has been executed. You can even put your own code in the commented area and find out how much memory it is using to execute the script. Due to nature of garbage collection ( https://www.php.net/gc ), the memory may not be immediately freed after the variable is marked unused in the script. There is no point in forcing garbage collection and leave it to PHP, garbage collector takes care of the memory management for you.

Take a look at our tutorial on how to manage and fix PHP memory issues

Make sure you unset all the variables declared in order to free up the memory. Also you may assign the variable to “null” to make that process faster.

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *