Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate system memory usage from /proc/meminfo (like htop)

Tags:

linux

memory

htop

Running the htop command gives you a picture of the memory usage in a format like this:

1.92G/5.83G

Question: how should I interpret the values taken from /proc/meminfo in order to calculate programmatically the memory used?

I am looking for something similar to this: Accurate calculation of CPU usage given in percentage in Linux? meaning that pseudocode is ok, I do not need something that can be compiled, just the logic. The source code of htop is a place to look for but I had no luck spotting the lines of code written for this...

$ cat /proc/meminfo 
MemTotal:        6110716 kB
MemFree:         2076448 kB
MemAvailable:    3800944 kB
Buffers:          382240 kB
Cached:          1496216 kB
SwapCached:            0 kB
Active:          2830192 kB
Inactive:         796648 kB
Active(anon):    1749940 kB
Inactive(anon):   109808 kB
Active(file):    1080252 kB
Inactive(file):   686840 kB
Unevictable:          48 kB
.
.
.
...
like image 769
tgogos Avatar asked Dec 19 '16 14:12

tgogos


People also ask

How is memory usage calculated?

The -/+ buffers/cache line shows how much memory is used and free from the perspective of the applications. Generally speaking, if little swap is being used, memory usage isn't impacting performance at all. So, the memory utilization for the server would be 154/503*100= 30%.

How much memory is configured in your PC cat Proc Meminfo?

On Linux you can use the command cat /proc/meminfo to determine how much memory the computer has. This command displays the information stored in the meminfo file located in the /proc directory. The total amount of memory will be displayed as MemTotal, shown in the example in bold.

How do I check memory usage on PID?

The ps command can also be used to monitor memory usage of individual processes. The ps v PID command provides the most comprehensive report on memory-related statistics for an individual process, such as: Page faults. Size of working segment that has been touched.


1 Answers

htop author here. These are the calculations I make to get the numbers for the green, blue and yellow bars in the memory meter:

  • Total used memory = MemTotal - MemFree
  • Non cache/buffer memory (green) = Total used memory - (Buffers + Cached memory)
  • Buffers (blue) = Buffers
  • Cached memory (yellow) = Cached + SReclaimable - Shmem
  • Swap = SwapTotal - SwapFree

In the htop source code: linux/LinuxProcessList.c and linux/Platform.c.

htop screenshot

like image 102
Hisham H M Avatar answered Oct 20 '22 07:10

Hisham H M