I've noticed there's quite a difference between what top
or ps
reports as memory usage for a PHP process, compared to what the process itself thinks its using (with memory_get_usage
).
How much memory is the process actually using?
When running the following code along with one of my apps:
echo "Memory usage: " . pretty_bytes(memory_get_usage()) . PHP_EOL;
echo "Peak memory usage: " . pretty_bytes(memory_get_peak_usage()) . PHP_EOL;
echo "'Actual' memory usage: " . pretty_bytes(memory_get_usage(true)) . PHP_EOL;
echo "'Actual' peak memory usage: " . pretty_bytes(memory_get_peak_usage(true)) . PHP_EOL;
$ps_output = exec("ps --pid " . getmypid() . " --no-headers -o rss");
echo "'Memory usage according to ps: " . pretty_bytes(intval($ps_output) * 1000);
The output at a random point was:
Memory usage: 4.77 MB
Peak memory usage: 4.99 MB
'Actual' memory usage: 5.00 MB
'Actual' peak memory usage: 5.00 MB
Memory usage according to ps: 17.66 MB
In my particular case, this is a concern because I'm running quite a few workers and daemons.
When I set the PHP memory limit to e.g. 128 MB for each of these daemons, the processes will only get killed once they reach 128 MB according to PHP's own measurements. However, according to ps
, the processes will be using around 200 MB each by that time.