Monitor a script's memory usage

 

HOW MUCH MEMORY DOES YOUR PHP SCRIPT USE?

 

 

PHP is not the most efficient language in the world, and sometimes PHP scripts can use a relatively large amount of system memory.

This happens quite often when working with large datasets, for example when handling large SQL result sets or when performing complex operations on large arrays.

 

You can check how much system memory your PHP script is using with the memory_get_usage() function.

This function returns the system memory currently used by the script (in bytes). You can also set the one function argument to TRUE to include inactive memory pages in the calculation.

 

A similar function is memory_get_peak_usage(), that returns the maximum amount of memory used by the script during its execution until that point.

 

It’s a good idea to use both functions when profiling your script. In the following example you can see how you can do it:

<?php

$big_array = array();

for ($i = 0; $i < 1000000; $i++)
{
	$big_array[] = $i;
}

print_mem();

unset($big_array);
print_mem();


function print_mem()
{
	/* Currently used memory */
	$mem_usage = memory_get_usage();
	
	/* Currently used memory including inactive pages */
	$mem_full_usage = memory_get_usage(TRUE);
	
	/* Peak memory consumption */
	$mem_peak = memory_get_peak_usage();

	echo 'This scrip now uses ' . round($mem_usage / 1024) . 'KB of memory.<br>';
	echo 'Real usage: ' . round($mem_full_usage / 1024) . 'KB.<br>';
	echo 'Peak usage: ' . round($mem_peak / 1024) . 'KB.<br><br>';
}

 

 

If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.

If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!

 

Alex