memory_get_peak_usage() with "real usage"

thelolcat picture thelolcat · Apr 1, 2013 · Viewed 70.3k times · Source

If the real_usage argument is set to true the PHP DOCS say it will get the real size of memory allocated from system. If it's false it will get the memory reported by emalloc()

Which one of these 2 options returns the max. memory allocated relative to the memory limit value in php.ini ?

I want to know how close was the script to hit that limit.

Answer

Niko Sams picture Niko Sams · Apr 26, 2013

Ok, lets test this using a simple script:

ini_set('memory_limit', '1M');
$x = '';
while(true) {
  echo "not real: ".(memory_get_peak_usage(false)/1024/1024)." MiB\n";
  echo "real: ".(memory_get_peak_usage(true)/1024/1024)." MiB\n\n";
  $x .= str_repeat(' ', 1024*25); //store 25kb more to string
}

Output:

not real: 0.73469543457031 MiB
real: 0.75 MiB

not real: 0.75910949707031 MiB
real: 1 MiB

...

not real: 0.95442199707031 MiB
real: 1 MiB

not real: 0.97883605957031 MiB
real: 1 MiB

PHP Fatal error:  Allowed memory size of 1048576 bytes exhausted (tried to allocate 793601 bytes) in /home/niko/test.php on line 7

Seems like real usage is the memory allocated from the system - which seems to get allocated in larger buckets than currently needed by the script. (I guess for performance reasons). This is also the memory the php process uses.

The $real_usage = false usage is the memory usage you actually used in your script, not the actual amount of memory allocated by Zend's memory manager.

Read this question for more information.

In short: to get how close are you to the memory limit, use $real_usage = true