Tracking Memory and Swap Usage

In Linux, there is a relatively simple way to track memory and swap usage by process.  First look to the directory “/procs”.  Here you will see a list of subdirectories named by running process ids (PIDs).  Each subdirectory contains files and other directories that contain useful information about that process.  For the metrics we want, we’ll focus on the “status” file, which looks something like this:

Name: python
State: R (running)
Tgid: 23349
Pid: 23349
PPid: 23323
TracerPid: 0
Uid: 502 502 502 502
Gid: 502 502 502 502
Utrace: 0
FDSize: 256
Groups: 502
VmPeak: 2577164 kB
VmSize: 2577164 kB
VmLck: 0 kB
VmHWM: 1301816 kB
VmRSS: 1301816 kB
VmData: 2307792 kB
VmStk: 116 kB
VmExe: 4 kB
VmLib: 37872 kB
VmPTE: 3232 kB
VmSwap: 0 kB
Threads: 24
SigQ: 0/2066244
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000001001000
SigCgt: 0000000180000002
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
Cpus_allowed: 200000
Cpus_allowed_list: 21
Mems_allowed: 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000002
Mems_allowed_list: 1
voluntary_ctxt_switches: 59
nonvoluntary_ctxt_switches: 60429509

For your reference, the list below describes the most interesting memory-related metrics:

VmPeak:	Peak virtual memory usage
VmSize:	Current virtual memory usage
VmLck:	Current mlocked memory
VmHWM:	Peak resident set size
VmRSS:	Resident set size
VmData:	Size of "data" segment
VmStk:	Size of stack
VmExe:	Size of "text" segment
VmLib:	Shared library usage
VmPTE:	Pagetable entries size
VmSwap:	Swap space used

To see a descending sorted list of swap space by process, we could use the following simple one-liner:

for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | less

To see a similar list for memory usage, we could use:

for file in /proc/*/status ; do awk '/VmRSS|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | less

Using the above, I’m sure you can come up with other ways to get useful process metrics. Enjoy!

Leave a Reply

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