PHP memory_get_usage is larger than memory_limit
Asked Answered
A

1

7

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.

Aster answered 7/8, 2013 at 13:10 Comment(2)
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 MBWeatherly
Your math is off by an order of magnitude. Divide it by another 1024 to get megabytes.Smelt
W
12

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>';
Weatherly answered 7/8, 2013 at 13:21 Comment(9)
I should quit my job :|Aster
Can happen to the best of us ;)Weatherly
memory_get_usage() is about allocated memory, not used memoryLasso
@YoushaAleayoub does allocated memory count for the script memory_limit ?Panta
@Panta memory_get_usage() returns Current allocated memory by single script while memory_limit sets Maximum amount of memory a single script is Allowed to allocate.Lasso
@YoushaAleayoub so I can use memory_get_usage() to check if I am about to hit the memory_limit and it will be the same value that is used internally? For example if((memory_get_usage()/128000000)>=0.9) break; ?Panta
@Panta Yes.Lasso
If the parameter is not set or FALSE only the used memory is reported.Mitchel
I copied this and my answer was 80M wtf??? think the issues is real for my case.Illyria

© 2022 - 2024 — McMap. All rights reserved.