CPU使用率:
int GetProcessInfo::GetProcessNumber() { SYSTEM_INFO info; GetSystemInfo(&info); return (int)info.dwNumberOfProcessors; } // 时间格式转换 __int64 GetProcessInfo::FileTimeToInt64(const FILETIME& time) { ULARGE_INTEGER tt; tt.LowPart = time.dwLowDateTime; tt.HighPart = time.dwHighDateTime; return(tt.QuadPart); } double GetProcessInfo::get_cpu_usage() { //cpu数量 static int processor_count_ = -1; //上一次的时间 static __int64 last_time_ = 0; static __int64 last_system_time_ = 0; FILETIME now; FILETIME creation_time; FILETIME exit_time; FILETIME kernel_time; FILETIME user_time; __int64 system_time; __int64 time; // __int64 system_time_delta; // __int64 time_delta; double cpu = -1; if(processor_count_ == -1) { processor_count_ = GetProcessNumber(); } GetSystemTimeAsFileTime(&now); HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION/*PROCESS_ALL_ACCESS*/, false, m_ProcessID); if (!hProcess) { return -1; } if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time)) { return -1; } system_time = (FileTimeToInt64(kernel_time) + FileTimeToInt64(user_time)) / processor_count_; //CPU使用时间 time = FileTimeToInt64(now); //现在的时间 last_system_time_ = system_time; last_time_ = time; CloseHandle( hProcess ); Sleep(1000); hProcess = OpenProcess(PROCESS_QUERY_INFORMATION/*PROCESS_ALL_ACCESS*/, false, m_ProcessID); if (!hProcess) { return -1; } if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time)) { return -1; } GetSystemTimeAsFileTime(&now); system_time = (FileTimeToInt64(kernel_time) + FileTimeToInt64(user_time)) / processor_count_; //CPU使用时间 time = FileTimeToInt64(now); //现在的时间 CloseHandle( hProcess ); cpu = ((double)(system_time - last_system_time_) / (double)(time - last_time_)) * 100; return cpu; }
内存使用:
void GetProcessInfo::PrintMemoryInfo() { HANDLE hProcess; PROCESS_MEMORY_COUNTERS pmc; DWORD dwPriorityClass; int memoryInK; SYSTEMTIME nowtime; GetLocalTime(&nowtime); CString nowdata = _T(""); nowdata.Format(_T("%d:%d"), nowtime.wHour,nowtime.wMinute); // 获得m_ProcessID的句柄 hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, m_ProcessID ); CString AppName; AppName.Format(_T("memory-%s"), nowdata); if (NULL == hProcess) { WritePrivateProfileString(AppName, m_ProcessName, _T("Can't Open The Process"), m_Address_ini); return; } dwPriorityClass = 0; dwPriorityClass = GetPriorityClass( hProcess ); if( !dwPriorityClass ) { WritePrivateProfileString(AppName, m_ProcessName, _T("GetPriorityClass"), m_Address_ini); return; } if (GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) { memoryInK = pmc.WorkingSetSize/1024; //单位为k CString memory; memory.Format(_T("%d"), memoryInK); WritePrivateProfileString(AppName, m_ProcessName, memory, m_Address_ini); } CloseHandle( hProcess ); }