sysinfo使C ++无效的可用内存报告

时间:2015-07-23 07:09:37

标签: c++ c linux memory

我试图获取目前在Linux下使用的物理内存量。我在How to determine CPU and memory consumption from inside a process?处理了答案。它似乎在我的计算机上工作正常,但当部署到DigitalOcean 512Mb服务器时,它开始报告一些奇怪的值。

根据htop系统使用了大约129Mb ram的490Mb可用。此处也是free -m的结果。

             total       used       free     shared    buffers     cached
Mem:           490        472         17          0        168        176
-/+ buffers/cache:        128        361
Swap:         1023          0       1023

上述答案中的公式为(sysinfo.totalram - sysinfo.freeram) * sysinfo.mem_unit。看起来我也应该采用“缓冲区”。并且'缓存'考虑列以获得正确的值。所以我写了一个简单的测试应用程序,以找出sysinfo结构中存储的内容。

#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);
}

结果如下:

totalRam 490
freeRam 17
sharedRam 0
bufferRam 168
totalSwap 1023
freeSwap 1023
totalHigh 0
freeHigh 0

看起来sysinfo.buffersram对应于&#39;缓冲区&#39; free -m的列,但是&#39;缓存&#39;是什么?值?什么是获得使用的物理内存量的正确方法?

0 个答案:

没有答案