如何在 C++ 中获得总 'percentage' RAM?

How to get the total 'percentage' of RAM in C++?

您好,我正在用 C++ 构建应用程序。我想获得 windows 机器正在使用的 RAM 的 百分比。我尝试了一些代码,例如:

string getRamUsage()
{
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;

    return to_string(physMemUsed);
}

但它只是 returns 一些装配值。我能得到解决方案吗?

您需要调用GlobalMemoryStatusEx获取数据。

MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);

// it already contains the percentage
auto memory_load = statex.dwMemoryLoad; 

// or calculate it from other field if need more digits.
auto memory_load = 1 - (double)statex.ullAvailPhys / statex.ullTotalPhys;

注意:您应该检查 GlobalMemoryStatusEx 的 return 值以防失败。