Technomancy

Entries tagged “snippet”

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:

mem_print(__LINE__);
, 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:

  mem_print(__LINE__);
  suspect_function();
  mem_print(__LINE__);

Show which directories have the most files (regardless of size)

written by rory, on Jan 21, 2010 11:51:00 AM.

I was rsync-ing a directory to remote host using an old version of rsync, so it had to count all the files on my local machine before it could start copying (newer versions of rsync start copying before reading all the files). However this was a large directory tree, with thousands and thousands of files, and it was taking rsync a long time to count. There are tools like ncdu to show how much disk space each folder is using. However in this case I want to reduce the number of files, regardless of their size, so ncdu is useless to me.

This bash snippet will show how many files & directories are in each folder, with the most 'populous' directories at the bottom.

find | cut -d/ -f2 | uniq -c | sort -n