得到cpu占有率的API函数:
GetSystemTimes
得到内存使用情况的API函数:
GlobalMemoryStatusEx Function
Retrieves information about the system's current usage of both physical and virtual memory.
GetPerformanceInfo Function
Retrieves the performance values contained in the PERFORMANCE_INFORMATION structure
获取特定程序的内存使用情况用:
GetProcessMemoryInfo Function
Retrieves information about the memory usage of the specified process.
#define _WIN32_WINNT 0x0501
#include <Windows.h>
#include <iostream>
using namespace std;
__int64 CompareFileTime ( FILETIME time1, FILETIME time2 )
{
__int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime ;
__int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime ;
return (b - a);
}
void main()
{
HANDLE hEvent;
BOOL res ;
FILETIME preidleTime;
FILETIME prekernelTime;
FILETIME preuserTime;
FILETIME idleTime;
FILETIME kernelTime;
FILETIME userTime;
res = GetSystemTimes( &idleTime, &kernelTime, &userTime );
preidleTime = idleTime;
prekernelTime = kernelTime;
preuserTime = userTime ;
hEvent = CreateEvent (NULL,FALSE,FALSE,NULL); // 初始值为 nonsignaled ,并且每次触发后自动设置为nonsignaled
while (1){
WaitForSingleObject( hEvent,1000 ); //等待500毫秒
res = GetSystemTimes( &idleTime, &kernelTime, &userTime );
int idle = CompareFileTime( preidleTime,idleTime);
int kernel = CompareFileTime( prekernelTime, kernelTime);
int user = CompareFileTime(preuserTime, userTime);
int cpu = (kernel +user - idle) *100/(kernel+user);
int cpuidle = ( idle) *100/(kernel+user);
cout << "CPU利用率:" << cpu << "%" << " CPU空闲率:" <<cpuidle << "%" <<endl;
preidleTime = idleTime;
prekernelTime = kernelTime;
preuserTime = userTime ;
}
}