Entries tagged “php”

PHP - How to track down a memory leak

written by rory, on Jan 25, 2010 4:04:40 PM.

I had to track down a bug in a PHP application. It was a long running maintenance script called from the command line. There was a memory leak and it was slowly growing in memory usage.

I created this little top level function:

$last_mem_usage = 0;
function mem_print($line_num) {
        global $last_mem_usage;
        $total = intval(memory_get_usage());
        print " at line $line_num  we have used ".number_format(intval($total - $last_mem_usage)). " since last total=$total last=$last_mem_usage\n";
        $last_mem_usage = $total;

Call it like so:

, and it will show you the memory usage since you last made that call.

If you suspect a certain function (or loop, or ...) of swollowing up your memory you can put it before or after the function call, like so: