C++调用windows.h显示电脑内存CPU

By | 2017年2月7日

分享一段c++调用windows.h,显示当前系统内存使用率,剩余内存,动态显示cpu使用率的代码,在c++编译器中编译好以后直接复制.exe使用即可。效果如下图。

c++
#include "iostream"
#include <stdio.h>
#include <conio.h>
#include <windows.h>
using namespace std;
const int KB_DIV = 1024;
const int MB_DIV = 1024 * 1024;
class CCPUUseRate<br />
{<br />
public:<br />
BOOL Initialize()<br />
{<br />
FILETIME ftIdle, ftKernel, ftUser;<br />
BOOL flag = FALSE;<br />
if (flag = GetSystemTimes(&ftIdle, &ftKernel, &ftUser))<br />
{<br />
m_fOldCPUIdleTime = FileTimeToDouble(ftIdle);<br />
m_fOldCPUKernelTime = FileTimeToDouble(ftKernel);<br />
m_fOldCPUUserTime = FileTimeToDouble(ftUser);

<pre><code> }
return flag;
}
//调用Initialize后要等待1秒再调用此函数
int GetCPUUseRate()
{
int nCPUUseRate = -1;
FILETIME ftIdle, ftKernel, ftUser;
if (GetSystemTimes(&ftIdle, &ftKernel, &ftUser))
{
double fCPUIdleTime = FileTimeToDouble(ftIdle);
double fCPUKernelTime = FileTimeToDouble(ftKernel);
double fCPUUserTime = FileTimeToDouble(ftUser);
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;
}
</code></pre>

private:<br />
double FileTimeToDouble(FILETIME &filetime)<br />
{<br />
return (double)(filetime.dwHighDateTime * 4.294967296E9) + (double)filetime.dwLowDateTime;<br />
}<br />
private:<br />
double m_fOldCPUIdleTime;<br />
double m_fOldCPUKernelTime;<br />
double m_fOldCPUUserTime;<br />
};<br />
int main(){
MEMORYSTATUS memStatus;
GlobalMemoryStatus(&memStatus);
cout<<"**************系统资源显示**************"<<endl<<endl;

<pre><code> printf("*******当前内存使用率:%d%%\n",memStatus.dwMemoryLoad);
printf("*******当前可用物理内存:%dKB(%dMB)\n",memStatus.dwAvailPhys / KB_DIV,memStatus.dwAvailPhys / MB_DIV);
CCPUUseRate cpuUseRate;
if (!cpuUseRate.Initialize())
{
printf("Error! %d\n", GetLastError());
getch();
return -1;
}
else
{
while (true)
{
Sleep(1000);
printf("\r当前CPU使用率为:%4d%%", cpuUseRate.GetCPUUseRate());
}
}

while(true){
Sleep(1000);

}
int a;cin>>a;
return 0;
</code></pre>

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注