Is there any command like time, but for memory usage?

Solution 1:

zsh has a more powerful built-in time command than bash has, and the zsh version can report memory statistics.

Even if you don't regularly use zsh as your day-to-day shell, you can just run it when you need to gather these kinds of statistics.

Set the TIMEFMT environment variable to indicate the output you want. Here is what I have in my .zshrc file (perhaps a bit too fancy, but I like it):

if [[ `uname` == Darwin ]]; then
    MAX_MEMORY_UNITS=KB
else
    MAX_MEMORY_UNITS=MB
fi

TIMEFMT='%J   %U  user %S system %P cpu %*E total'$'\n'\
'avg shared (code):         %X KB'$'\n'\
'avg unshared (data/stack): %D KB'$'\n'\
'total (sum):               %K KB'$'\n'\
'max memory:                %M '$MAX_MEMORY_UNITS''$'\n'\
'page faults from disk:     %F'$'\n'\
'other page faults:         %R'

(A complicated detail: On Linux, max memory is megabytes; on macOS it's in kilobytes. To get the value for %M, zsh calls getrusage(), and then uses ru_maxrss / 1024. but on Linux, ru_maxrss is in kilobytes, and on Mac it's in bytes. See man getrusage on both platforms.)

Sample output:

% time ls
[... the output of ls, followed by:]
ls -G   0.00s  user 0.00s system 91% cpu 0.004 total
avg shared (code):         0 KB
avg unshared (data/stack): 0 KB
total (sum):               0 KB
max memory:                3 MB
page faults from disk:     0
other page faults:         337

Solution 2:

GNU time can report a bit more information than the version built into Bash; use command time rather than just time to invoke it, and see the man page or info for details.

Solution 3:

Based on Richard's answer, you can create an alias to use GNU time and provide average and maximum memory information:

alias time="$(which time) -f '\t%E real,\t%U user,\t%S sys,\t%K amem,\t%M mmem'"

or adjust your environment:

export TIME='\t%E real,\t%U user,\t%S sys,\t%K amem,\t%M mmem'

But be aware that this only works for /usr/bin/time which is often not called by default.

From the man page:

K Average total (data+stack+text) memory use of the process, in Kilobytes.

M Maximum resident set size of the process during its lifetime, in Kilobytes.