How to calculate memory utilization percentage in linux machine?

8.3k views Asked by At

I'm writing a script to calculate Memory Utilization Percentage in a Linux system. My script will be deployed in production which has many flavours of Linux CentOS.

So far, I have used free command, but there seems to be a problem with one OS version or the other.Problem is in some servers( eg. Linux CentOS 7.5.1804 (3.10.0-862.14.4.el7.x86_64)) , MEM% is more than 100, as the free command output differs in them. Keeping in mind the formula,

MEM%= 100-(((free+buffers+cached)*100)/TotalMemory). 

I need a script to calculate memory percentage no matter what the flavour of OS it is.

I have tried calculating memory from top command | grep "Mem:" , but it is very arbitrary.

Thus I'm using the formula I have now.

It's ok that memory calculation can be complex and I just want reasonable percentage value which is close to real value .Any suggestion would be highly helpful.

total_perc=100
average=$( free -b | grep ":" | head -1 | tr -s ' ' | cut -d ':' -f2 | awk '{$1=$1};1' )
a1=$(echo $average | cut -d ' ' -f1) # Total
a2=$(echo $average | cut -d ' ' -f2) #Used
a3=$(echo $average | cut -d ' ' -f3) #Free
a4=$(echo $average | cut -d ' ' -f4) #Shared
a5=$(echo $average | cut -d ' ' -f5) #Buffers
a6=$(echo $average | cut -d ' ' -f6) #Cached
addition=$(( a3 + a5 + a6 ))
multi=$(( addition*100))
divis=$(awk -v dividend="${multi}" -v divisor="${a1}" 'BEGIN {printf "%.2f", dividend/divisor; exit(0)}')
percentage=$(awk -v no1="${total_perc}" -v no2="${divis}" 'BEGIN {printf "%.2f", no1-no2; exit(0)}')
echo "Final Memory Util Percentage : $percentage"

In some OS flavours, such as :Linux CentOS 7.5.1804 (3.10.0-862.14.4.el7.x86_64)", the utilization percentage crosses, 100.Kinldy guide me where I'm going wrong.

I need a OS flavour independent code for calculating Memory. Thanks in Advance.

1

There are 1 answers

0
Bogdan On

Instead of using the free command, a much more straightforwad way would be to look in /proc/meminfo:

grep -oP '^MemFree: *\K[0-9]+' /proc/meminfo

This should would with all the kernels from the last decade. Also, this approach asks the kernel about free memory. Tools would also ask the kernel and apply some additional calculations so you'd actually have to understand what the tools are doing to see if your calculation is reliable.