How to monitor memory usage in linux server

1. Use free command

$free -h -t
total used free shared buff/cache available
Mem: 7.7Gi 2.8Gi 1.2Gi 1.2Gi 3.6Gi 3.3Gi
Swap: 2.0Gi 0B 2.0Gi
Total: 9.7Gi 2.8Gi 3.2Gi

Mem:
total – total amount of memory that can be used by the applications.
used – Used memory. Calculated as: total – free – buffers – cache
free – Unused memory.
shared – Memory that is used by the tmpfs file system.
buff/cache – Memory used for buffers and cache
available – This is an estimation of the memory that is available to service memory requests from applications.

Swap:
total: Size of the swap partition or swap file.
used: Swap space in use.
free: Unused swap space

Total:
Sum of the memory and swap in the total

Note, for efficiency purpose, Linux uses physical memory that is not needed by running programs as a file cache for efficiency. But if programs need that physical memory, the kernel will reallocate the file cache memory to the programs. So memory shows in column “buff/cache”consider to be free.

2. Top 10 users which are consuming more memory on system in percentage

$ps -eo user,pcpu,pmem | tail -n +2 | awk '{num[$1]++; cpu[$1] += $2; mem[$1] += $3} END{printf("NPROC\tUSER\tCPU\tMEM\n"); for (user in cpu) printf("%d\t%s\t%.2f\t%.2f\n",num[user], user, cpu[user], mem[user]) }'
NPROC USER CPU MEM

3. Top 10 processes that are consuming RSS ( Resident Set Size )

$ps -e -orss,pid=,user=,args=, | sort -b -k1,1n | pr -TW$COLUMNS| tail -10

Result column are: RSS, PID, USER and Command Executed.

Note RSS here shows how much memory the process has actually allocated in KB

4. Memory usage detail of every process active on the system (more accurate than RSS)

# smem -k -t
PID User Command Swap USS PSS RSS
727 root /usr/sbin/acpid 0 232.0K 239.0K 2.0M
732 root /usr/sbin/cron -f 0 312.0K 326.0K 2.9M
... output trimmed 
-------------------------------------------------------------------------------
225 12 0 3.6G 4.0G 9.1G

Smem is a tool can report USS (Unique Set Size) and PSS (Proportional Set Size).

Depend on operation system. to install smem:

sudo yum install smem
sudo apt-get install smem

PSS numbers for each process will match sum of /proc/PID/maps. In other word it is what we have been looking for.

Command to see real memory usage (PSS and RSS) sum up of one process info in /proc/PID/smaps:

cat /proc/PID/smaps | grep -i pss | awk '{Total+=$2} END {print Total/1024" MB"}'
cat /proc/PID/smaps | grep -i rss | awk '{Total+=$2} END {print Total/1024" MB"}'
example:
# cat /proc/283/smaps | grep -i rss | awk '{Total+=$2} END {print Total/1024" MB"}'
95.2148 MB

5. swap memory usage

$vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 1198292 198892 3586468 0 0 13 19 15 140 10 2 88 0 0

Watch out high si and so (swap in and out) value as well as a high percentage of swap space used (from free command result).

Leave a Reply