I'm trying to get the amount of physical memory currently used under Linux. I've followed the answer at How to determine CPU and memory consumption from inside a process? It appeared to work fine on my computer, but when deployed to DigitalOcean 512Mb server it started reporting some weird values.
According to htop
system was using around 129Mb ram out of 490Mb available. Also here's the result of free -m
.
total used free shared buffers cached
Mem: 490 472 17 0 168 176
-/+ buffers/cache: 128 361
Swap: 1023 0 1023
Formula from the mentioned answer was (sysinfo.totalram - sysinfo.freeram) * sysinfo.mem_unit
. It looks like I should also take the 'buffers' and 'cached' columns into account to get the correct value. So I wrote a simple test app to find out what's stored in the sysinfo
structure.
#include <cstdio>
#include <sys/sysinfo.h>
int main()
{
struct sysinfo memInfo;
sysinfo (&memInfo);
long long int physMemUsed = memInfo.totalram - memInfo.freeram;
physMemUsed *= memInfo.mem_unit;
printf("totalRam %lld\n", (long long int)memInfo.totalram * memInfo.mem_unit / 1024 / 1024);
printf("freeRam %lld\n", (long long int)memInfo.freeram * memInfo.mem_unit / 1024 / 1024);
printf("sharedRam %lld\n", (long long int)memInfo.sharedram * memInfo.mem_unit / 1024 / 1024);
printf("bufferRam %lld\n", (long long int)memInfo.bufferram * memInfo.mem_unit / 1024 / 1024);
printf("totalSwap %lld\n", (long long int)memInfo.totalswap * memInfo.mem_unit / 1024 / 1024);
printf("freeSwap %lld\n", (long long int)memInfo.freeswap * memInfo.mem_unit / 1024 / 1024);
printf("totalHigh %lld\n", (long long int)memInfo.totalhigh * memInfo.mem_unit / 1024 / 1024);
printf("freeHigh %lld\n", (long long int)memInfo.freehigh * memInfo.mem_unit / 1024 / 1024);
}
And here's the result:
totalRam 490
freeRam 17
sharedRam 0
bufferRam 168
totalSwap 1023
freeSwap 1023
totalHigh 0
freeHigh 0
It looks like sysinfo.buffersram
corresponds to 'buffers' column of free -m
, but what's the 'cached' value? What's the proper way to get the amount of used physical memory?