Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory_limit: How does it work?

I have a php script that runs for about 2 hours. It is a cron job. The cron job runs every 4 hours.

At the end of the script, I display some memory values.

The memory_get_usage() result is 881568 Bytes (0.840766906738M)
The memory_get_peak_usage() result is 1340304 Bytes (1.27821350098M)
The memory_get_usage(true) result is 1572864 Bytes (1.5M)
The memory_get_peak_usage(true) result is 1835008 Bytes (1.75M)

The memory_limit in php.ini was 128M and it didn't work. I raise it to 256M and now it works.

But as the memory peak of the script is less than 2M....

So how does the memory_limit parameter work?

Is it the total memory used by the script? If so, how can I calculate it?

Is it the memory peak of the script? if so, am I calculating it right?

I'm using php 5.3.16.

EDIT

I don't have any error messages. When the limit was 128M The script executes, but never finishes.

like image 594
Marm Avatar asked Sep 06 '12 14:09

Marm


1 Answers

Try using a function that uses your operating system to report actual memory such as this one.

function unix_get_usage() { 
      $pid = getmypid(); 
      exec("ps -o rss -p $pid", $output); 
      return $output[1] *1024; 
 }

function windows_get_usage(){
    $output = array();
    exec('tasklist /FI "PID eq '.getmypid().'" /FO LIST', $output );
    return preg_replace( '/[^0-9]/', '', $output[5] ) * 1024;
}

Your script probably consumes a lot of memory that PHP doesn't consider when returning from memory_get_usage() (which looks at the heap btw). Stack allocated variables would have been cleared up by the time memory_get_usage() was called and returned.

You should also try running this function and others at other points during execution, e.g. after big MySQL calls or file processing. memory_get_peak_usage() may not work on all OS's, especially depending on compile options.

like image 199
Jared Kipe Avatar answered Nov 18 '22 19:11

Jared Kipe