Measuring memory usage with strace

In the tradition of abusing high-level Linux tools to produce useful low-level data, I present a method for estimating peak memory usage in Linux by text-processing the output from strace:

This Perl script invokes an arbitrary command via strace. It adds up memory allocated by mmap2() with no location hint and the file handle set to -1, this is the way that malloc() typically allocates large amounts of memory. It also counts calls to brk(), and subtracts the sizes of munmap() calls for maps that were previously counted. It outputs the current memory usage rounded off to the nearest megabyte, whenever that number changes.

Other methods for measuring peak memory usage typically revolve around polling /proc for resident set size (RSS), this potentially misses short-lived allocations. The GNU time command (/usr/bin/time, not the one built in to bash) can show peak RSS, but in some applications this can be a vast overestimate of physical memory usage, due to the way Linux counts RSS.

My method provides a reasonable estimate of the amount of memory allocated with malloc(). That can be a useful thing to know.

Leave a Reply

Your email address will not be published. Required fields are marked *