How to get % memory usage with vmstat?

What you're looking for is the output from "free":

$ free
             total       used       free     shared    buffers     cached
Mem:        775556     759456      16100          0      22132     592484
-/+ buffers/cache:     144840     630716
Swap:       500344      21972     478372

Here's a tour:

This is a box w/ 768MB of physical RAM and a 500344KB swap partition.

759456KB is "used" (second column, top row). Of this "used" memory, 23132KB is buffers (5th column, top row) and 592484KB (sixth column, top row) is cache, leaving 144840KB (2nd column, 2nd row) of physical memory that's being used by active processes.

When you consider that the memory used by buffers and cache could be used for processes, that leaves 630716KB (3rd column, 2nd row) of physical memory free.

The swap partition, as I said, is 500344KB (1st column, bottom row). 21972KB (2nd column, bottom row) of the swap file is in use, leaving 478372KB (3rd column, bottom row) free.

So, your definition of % free memory depends on whether you're counting buffers and cache or not, and whether you're counting swap or not.

That ought to give you enough to go on to calculate a percentage as you see fit.


Here's the output of top and free:

$ top -n1 | grep "used," ; free
Mem:    775556k total,   751472k used,    24084k free,    20776k buffers
Swap:   500344k total,    21972k used,   478372k free,   586648k cached

             total       used       free     shared    buffers     cached
Mem:        775556     751344      24212          0      20776     586648
-/+ buffers/cache:     143920     631636
Swap:       500344      21972     478372

You can see how top and free agree (albeit with a little difference-- this is a multi-user machine and the memory usage of the top and free programs are reflected in there).


Add a "-s" when you call vmstate, and you will see much the same output, just in a different form:

$ vmstat -s ; free
       775556  total memory
       759920  used memory
       674680  active memory
        18440  inactive memory
        15636  free memory
        21892  buffer memory
       594372  swap cache
       500344  total swap
        21972  used swap
       478372  free swap
       ... output truncated ...

             total       used       free     shared    buffers     cached
Mem:        775556     759920      15636          0      21892     594372
-/+ buffers/cache:     143656     631900
Swap:       500344      21972     478372

You can see that vmstat is showing all the same numbers as free.


I have same question with you and come up with a formula

vmstat -s | awk  ' $0 ~ /total memory/ {total=$1 } $0 ~/free memory/ {free=$1} $0 ~/buffer memory/ {buffer=$1} $0 ~/cache/ {cache=$1} END{print (total-free-buffer-cache)/total*100}'

I have tested it on vmstat version from procps-ng 3.3.10 and vmstat from procps-ng 3.3.9