Pages

Saturday, November 12, 2011

Get the current used memory with ps

Last time I had a customer complaining about his 72GB RAM machine that it was swapping. Then he told me that all processes were using 0% RAM. He showed me something like this:

# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
...
oracle    4539  0.0  0.0    708 48264 ?        Ss    2008  16:23 ORACLE
...

This is so wrong in so many ways! From my point of view the %MEM column in ps is totally useless these days. What is much more important is the RSS column. It shows the used memory in KB. So the oracle process shown above uses 48264KB of memory. More worse was the number of processes currently running:

# ps aux | wc -l
3122

His operating system was running 3122 processes. Assuming that 122 processes were needed by the operating system then 3000 processes were used by Oracle. Now a small sample calculation:

# echo 3000*50000 | bc
150000000

3000 times 50KB are 150000000KB in sum. Now devide it by 1024 two times to get the amount in GB:

# echo 150000000/1024/1024 | bc -l
143.05114746093750000000

His machine uses about 143GB of memory, but he has only 72GB of physical memory. No wonder that his machine was swapping. By the way: 50MB of 72GB are about 0.0%.
To get the current used memory by a process use the RSS column in ps:

# ps -eo rss,cmd
  RSS CMD
...
 6716 /usr/bin/python /opt/mailman/bin/qrunner --runner=RetryRunner:0:1 -s
..
 9160 /usr/bin/httpd -k start
...

Now you can do some real useful stuff. First remove the cmd column in ps:

# ps -eo rss
  RSS
...
26700
 1000
 5200
...

Then use grep to get rid of the ps header:

# ps -eo rss | grep -v RSS
...
26700
 1000
 5200
...

Finally you can use awk to get the sum of all values:

# ps -eo rss | grep -v RSS | awk '{total = total + $1} END {print total}'
246000

This is one of my small webservers - just a very simple LAMP environment. It has 2GB memory available and is currently using ~240MB.