PHP memory_get_usage is larger than memory_limit

Nahuel picture Nahuel · Aug 7, 2013 · Viewed 11.5k times · Source

My PHP application has been running a bit slow and it's not very memory efficient at the moment. My whole server has been going down very often and I think I have this app to blame. I thought I'd monitor the memory usage and check how much I have as a limit:

echo 'Memory in use: ' . memory_get_usage() . ' ('. memory_get_usage()/1024 .'M) <br>';
echo 'Peak usage: ' . memory_get_peak_usage() . ' ('. memory_get_peak_usage()/1024 .'M) <br>';
echo 'Memory limit: ' . ini_get('memory_limit') . '<br>';

This shows the following:

Memory in use: 629632 (614.921875M) 
Peak usage: 635696 (620.796875M) 
Memory limit: 128M

How could this be? Memory in use is WAY larger than memory limit? Either something's really broken or I do not understand at all how the memory_limit setting works (or memory_get_usage() )

Thank you all.

Answer

AmazingDreams picture AmazingDreams · Aug 7, 2013

memory_get_usage returns it in bytes, what you are calculating there is actually in kB. Divide it by 1024 again to have it in MB

Same goes for memory_get_peak_usage

e.g.

echo 'Memory in use: ' . memory_get_usage() . ' ('. ((memory_get_usage() / 1024) / 1024) .'M) <br>';