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

algorain

分享一段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
{
public:
BOOL Initialize()
{
FILETIME ftIdle, ftKernel, ftUser;
BOOL flag = FALSE;
if (flag = GetSystemTimes(&ftIdle, &ftKernel, &ftUser))
{
m_fOldCPUIdleTime = FileTimeToDouble(ftIdle);
m_fOldCPUKernelTime = FileTimeToDouble(ftKernel);
m_fOldCPUUserTime = FileTimeToDouble(ftUser);

 } 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; } 
private:
double FileTimeToDouble(FILETIME &filetime)
{
return (double)(filetime.dwHighDateTime * 4.294967296E9) + (double)filetime.dwLowDateTime;
}
private:
double m_fOldCPUIdleTime;
double m_fOldCPUKernelTime;
double m_fOldCPUUserTime;
};
int main(){ MEMORYSTATUS memStatus; GlobalMemoryStatus(&memStatus); cout<<”**************系统资源显示**************“<<endl<<endl;
 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; 
} ```

  • Title: C++调用windows.h显示电脑内存CPU
  • Author: algorain
  • Created at: 2017-02-07 21:55:33
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/02/07/c-article33/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments