獲取CPU利用率 系統記憶體和程序記憶體
阿新 • • 發佈:2019-02-09
#include <iostream> #include <windows.h> #include <Psapi.h> using namespace std; __int64 CompareFileTime(FILETIME t1,FILETIME t2) { __int64 a = t1.dwHighDateTime << 32 | t1.dwLowDateTime; __int64 b = t2.dwHighDateTime << 32 | t2.dwLowDateTime; return (b - a); } int GetCpuUsage() { HANDLE hEvent; FILETIME preidleTime; FILETIME prekernelTime; FILETIME preuserTime; FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; GetSystemTimes(&idleTime, &kernelTime, &userTime); preidleTime = idleTime; prekernelTime = kernelTime; preuserTime = userTime; hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); WaitForSingleObject(hEvent, 500); GetSystemTimes(&idleTime, &kernelTime, &userTime); __int64 idle = CompareFileTime(preidleTime, idleTime); __int64 kernel = CompareFileTime(prekernelTime, kernelTime); __int64 user = CompareFileTime(preuserTime, userTime); __int64 iCpuUsage = -1; iCpuUsage = (kernel + user - idle) * 100 / (kernel + user); return iCpuUsage; } int main() { //獲取系統記憶體使用率 MEMORYSTATUS ms; GlobalMemoryStatus(&ms); cout << "Mem usage = " << ms.dwMemoryLoad << endl; //獲取程序的記憶體(Private Bytes) PROCESS_MEMORY_COUNTERS pmc; GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(PROCESS_MEMORY_COUNTERS)); cout << "Current Process Mem usage = " << pmc.PagefileUsage << endl; //獲取當前系統的CPU利用率 __int64 iCpuUsage = GetCpuUsage(); cout << "CPU usage = " << iCpuUsage << endl; return 0; }