Find Out Process Memory Usage

Comments

Figuring out how much memory a process is using can be tricky due to the way Linux does memory management. However, here is a one-liner that will help you find out more about how much memory a process is using:

echo 0 $(cat /proc/PID/smaps | grep TYPE | awk '{print $2}' | sed 's#^#+#') | bc

Note that you should run this as root to get proper results. In addition, ‘PID’ is the process ID and ‘TYPE’ is one of the following examples:

  • Rss: Resident memory usage - this is all the memory a processes uses (including memory shared with other processes) but not swap
  • Shared: Memory that this process shares with other processes
  • Private: private memory used by this process
  • Swap: swap memory used by the process
  • Pss: Proportional Set Size - basically Rss memory adjusted for shared memory. For example, if a process has 1MB private and 20MB shared between other 10 processes, Pss is 1 + 20/10 = 3MB

The returned number will be in kilobytes. For example the Pss value of the MySQL daemon on my machine is currently 58897 kilobytes:

$ echo 0 $(cat /proc/1179/smaps | grep Pss | awk '{print $2}' | sed 's#^#+#') | bc
58897

You don’t have to stick to looking at single processes either. For example, here is a wonderfully useful script by Erik Ljungstrom that goes through all the processes and shows you their swap usage:

#!/bin/bash
# Get current swap usage for all running processes
# Erik Ljungstrom 27/05/2011

SUM=0
OVERALL=0
for DIR in `find /proc/ -maxdepth 1 -type d | egrep "^/proc/[0-9]"` ; do
  PID=`echo $DIR | cut -d / -f 3`
  PROGNAME=`ps -p $PID -o comm --no-headers`

  for SWAP in `grep Swap $DIR/smaps 2>/dev/null| awk '{ print $2 }'`; do
    let SUM=$SUM+$SWAP
  done

  echo "PID=$PID - Swap used: $SUM - ($PROGNAME )"
  let OVERALL=$OVERALL+$SUM
  SUM=0
done
echo "Overall swap used: $OVERALL"

Scripts like these are really useful for server monitoring :) Like the one-liner this needs to be run as root to get accurate results (otherwise it will return 0 for processes you don’t have access to), however that shouldn’t be a problem as you can use sudo if you’re worried about security.

Next Post
Generate SSH Keys

Previous Post
3 Simple Server Changes to Boost Website Performance


comments powered by Disqus