Hi I am building an application in C . I want get the percentage of RAM that a windows machine is using. I tried a few codes like:
string getRamUsage()
{
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
return to_string(physMemUsed);
}
but it just returns some assembly value. Can I get a solution?
CodePudding user response:
You need to call GlobalMemoryStatusEx
to get the data.
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;
note: you should check the return value of GlobalMemoryStatusEx
in case it fail.