Linux Process Memory Usage

For many years I've been confounded by Linux's memory usage. The main confusion comes from the use of shared libraries: do you count the shared library's memory usage toward the memory usage of the process that loaded it? If you have several processes that each share a large library, then you'll appear to have much more memory in use than is actually used - possibly more than your real memory. And then there's swapped out memory if you have a swap partition - do you count that? It's not using RAM, but it is using "memory" ... it's all so confusing.

The best explanation I've found of the commonest memory parameters (those shown by ps ax) comes - unsurprisingly - from Stack Overflow:

RSS is the Resident Set Size and is used to show how much memory is allocated to that process and is in RAM. It does not include memory that is swapped out. It does include memory from shared libraries as long as the pages from those libraries are actually in memory. It does include all stack and heap memory.

VSZ is the Virtual Memory Size. It includes all memory that the process can access, including memory that is swapped out and memory that is from shared libraries.

You should read the whole thing - I've included the link in the Bibliography below. He also linked to another explanation on how PSS and Dirty Memory are probably the "best" measures of process memory usage (link also included below), which inspired me to write the following script (because what we really need is more numbers, we don't have enough yet ...). Given a single process name, this will find all matching processes in the output of ps ax and then retrieve their "Dirty Memory" usage from the proc file system and add it up, printing a number for each PID.

#!/bin/bash
# Find the dirty memory usage for a given process name
# http://stackoverflow.com/questions/118307/a-way-to-determine-a-processs-real-memory-usage-i-e-private-dirty-rss

if [ $# -ne 1 ]
then
    echo "$(basename ${0}) <process-name>"
    echo "  Provide the name of an existing process"
    echo "  This script will show you dirty memory usage for that process."
    exit 1
fi

# header:
echo -e "PID\t\tDirty Memory"

for procid in $(ps ax | grep ${1} | grep -v grep | grep -v $(basename ${0}) | awk '{ print $1 }')
do
    let pdirty=0
    for usedmem in $(cat /proc/${procid}/smaps | grep Private_Dirty | awk '{ print $2 }')
    do
        let pdirty=$((pdirty + usedmem))
    done
    echo -e "${procid}\t\t${pdirty} KB"
done

I publish this with precisely zero promises of performance, and likewise no guarantees that it's doing anything useful at all. By the way ... this also requires root access to go digging through the /proc/ directory structure.