我正在使用 Sysinfo 库来计算 ram 使用情况,但它在 RPI4 和 CM4 中给出了不同的结果。它在 RPi4 中运行良好,但在 CM4 中返回荒谬的值。例如,
Sysinfo 返回 totalram 300kB,freeram 308kB,bufferram 9kB。
我查看了它可能是由于内核版本的可能性,但版本没有区别。
- CM4(Raspbian) 内核版本 5.10.63-v7l+
- RPI4(Raspbian) 内核版本 5.10.17-v7l+
代码 :
inline static void GetRamCache ()
{
char iwbuffer[1024];
memset(iwbuffer, 0, 1024);
FILE *iwFile;
std::string cmd = "cat /proc/meminfo | grep Cached | awk '{print $2}' | head -n 1";
iwFile = popen(cmd.c_str(), "r");
fread(iwbuffer, 1, sizeof(iwbuffer) - 1, iwFile);
fclose(iwFile);
mCachedRam = std::stoul(std::string(iwbuffer),nullptr,0);
}
inline static double GetMemoryUsagePercent (bool ForceGetMemoryCache = true)
{
unsigned long mFreeRam = 0;
unsigned long mBufferRam = 0;
unsigned long mRamUsed = 0;
double mPercentageRamUsed = 0;
struct sysinfo RamInfo;
if(mCachedRam == 0 || ForceGetMemoryCache)
{
GetRamCache();
}
try
{
if(sysinfo(&RamInfo) != -1)
{
mFreeRam = RamInfo.freeram / 1024; // byte to kB.
mBufferRam = RamInfo.bufferram / 1024;
if(mTotalRam == 0)
{
mTotalRam = RamInfo.totalram / 1024;
}
mRamUsed = (mTotalRam - (mFreeRam + mBufferRam + mCachedRam)) ; //kB
mPercentageRamUsed = (((double)mRamUsed / (double)mTotalRam) * 100);
}
}
catch(...)
{
std::cout << "GetMemoryUsagePercent EX1" << std::endl;
}
return mPercentageRamUsed;
}