As already mentioned, memory_get_usage
captures memory expenditure at the moment . However, there is another function, memory_get_peak_usage
, which takes the peak of maximum registered memory.
Note: both memory_get_usage
and < a href="http://php.net/manual/en/function.memory-get-peak-usage.php"> memory_get_peak_usage
"only gets the result defined by emalloc()
is returned.
So the differences are:
-
memory_get_usage returns the approximate current memory spend , 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 by PHP, it also varies if you are using extensions like Opcache
or XCache
-
memory_get_peak_usage returns peak memory 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 stay and always increase.
Testing at the end of the script
There is a function called register_shutdown_function
that runs at the end of the script, it would be like a "% global_content", at this point it is interesting to do the peak memory check, like this:
<?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 finished (those that are included do not fire this function unless there is a __destruct
or exit;
) and will add the result of the output / output / body of the document to the end of the output / how much was spent.
Note: die('foo');
can be added at any time before shutdown
Here about extensions