获取CPU和内存的使用率

时间:2020-12-03 05:53:22

1.获取CPU的使用率

主要就是一个计算。

int CUseRate::GetCPUUseRate()                    //获取CPU使用率
{
int nCPUUseRate = -1;
FILETIME ftIdle, ftKernel, ftUser;
if (GetSystemTimes(&ftIdle, &ftKernel, &ftUser))
{
double fCPUIdleTime = FileTimeToDouble(ftIdle);
double fCPUKernelTime = FileTimeToDouble(ftKernel);
double fCPUUserTime = FileTimeToDouble(ftUser);
//CPU利用率公式
nCPUUseRate= (int)(100.0 - (fCPUIdleTime - m_fOldCPUIdleTime) / (fCPUKernelTime - m_fOldCPUKernelTime + fCPUUserTime - m_fOldCPUUserTime) *100.0);
m_fOldCPUIdleTime
= fCPUIdleTime;
m_fOldCPUKernelTime
= fCPUKernelTime;
m_fOldCPUUserTime
= fCPUUserTime;
}
return nCPUUseRate;
}

2.获取内存使用率 

调用GlobalMemoryStatusEx函数获取

long long CUseRate::getRam()                //获取当前内存使用率
{
long long ram;
MEMORYSTATUSEX statex;
statex.dwLength
=sizeof(statex);
GlobalMemoryStatusEx(
&statex);
ram
= statex.dwMemoryLoad;
return ram;
}

3.结果获取CPU和内存的使用率

 

 

工程源码:http://download.csdn.net/detail/qq_33892166/9889310