As has already been quoted, memory_get_usage
captures current memory expenditure. However, there is another function, the memory_get_peak_usage
, that picks up the maximum recorded memory peak.
Note: so much memory_get_usage
how much memory_get_peak_usage
only achieves the result defined by emalloc()
is returned.
So the differences are:
memory_get_usage returns the approximate current memory expense, for example:
<?php
echo round(memory_get_usage() / 1024, 4), 'Kb', PHP_EOL; // 219.2656Kb
$a = str_repeat("Hello", 4242);
echo round(memory_get_usage() / 1024, 4), 'Kb', PHP_EOL; // 240.1797Kb
unset($a);
echo round(memory_get_usage() / 1024, 4), 'Kb', PHP_EOL; // 219.3125Kb
The values vary depending on the system and version used of PHP, also varies if using extensions such as Opcache
or XCache
memory_get_peak_usage returns the memory peak spent so far, then
<?php
echo round(memory_get_peak_usage() / 1024, 4), 'Kb', PHP_EOL; // 222.8906Kb
$a = str_repeat("Hello", 4242);
echo round(memory_get_peak_usage() / 1024, 4), 'Kb', PHP_EOL; // 241.7422Kb
unset($a);
echo round(memory_get_peak_usage() / 1024, 4), 'Kb', PHP_EOL; // 241.8047Kb
See that the numbers remain and always increase.
Testing at the end of the script
There is a function called register_shutdown_function
which runs at the end of the script, would be like a "__destruct
", at this point it is interesting to check the memory peak, thus:
<?php
register_shutdown_function(function() {
echo PHP_EOL, round(memory_get_peak_usage() / 1024, 4), 'Kb';
});
$a = str_repeat("Hello", 4242);
unset($a);
So whenever the larger script is terminated (those that are included do not trigger this function unless there is a exit;
or die('foo');
) and will add to the end of the output/output/body of the document the result of how much was spent.
Note: register_shutdown_function
may be added at any time before the shutdown
Here about extensions
Related: What is the difference between "memory_get_usage" and "memory_get_peak_usage"?
– Wallace Maxters