Analyzing memory usage on Linux
Find the processes that use the most memory on Linux and read the free, available and cache figures correctly.
Linux uses free RAM for the page cache and disk buffers, so tools that show "used" memory can look almost full while plenty of memory is still available to applications. This article shows how to find the processes that use the most memory and how to read the system-wide figures.
Memory used per process
Sort processes by resident memory (RSS, physical memory in use) or virtual memory (VSZ):
ps -aux --sort -rss
ps -aux --sort -vsz
| Column | Meaning |
|---|---|
| USER | User running the process |
| PID | Process ID |
| RSS | Physical memory used by the process |
| VSZ | Virtual memory size of the process |
Top 5 processes by percentage of memory:
ps -eo pmem,pid,cmd | sort -k 1 -nr | head -5
Total RSS of all processes:
ps -e -orss=,pid=,user=,args= | sort -b -k1,1n | pr -TW$COLUMNS | awk '{total += $1} END{print "sum="total}'
Swap used per process:
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r
System-wide memory
free -m shows the memory totals in megabytes. On current distributions, read the available column: it estimates how much memory can be given to new applications without swapping. On older versions, use the -/+ buffers/cache line, which gives the memory really used and really free once buffers and cache are excluded.
Available memory can be approximated as: total - used + buffers + cache.
To sample memory over time with sar (package sysstat):
sar -r 1 10
The columns kbmemfree, kbbuffers and kbcached give the free memory: kbmemfree + kbbuffers + kbcached.
Shared memory and IPC
IPC (inter-process communication) resources are pipes, shared memory, message queues and semaphores. The ipcs command lists them:
| Command | Shows |
|---|---|
ipcs -m -c |
Shared memory segments, with creator and owner |
ipcs -s -t |
Semaphores, with access and change times |
ipcs -u |
Summary of IPC usage |
ipcs -l |
System limits for IPC resources |
Notes
- The sum of RSS values counts shared pages once per process, so it can exceed the memory really in use.
- The kernel frees cache automatically when applications need memory. A high
buff/cachevalue alone is not a problem; checkavailableinstead. - Background reading: linuxatemyram.com and the Unix & Linux Stack Exchange thread on memory usage.