1. 程式人生 > >獲取當前程序的CPU使用率和記憶體使用

獲取當前程序的CPU使用率和記憶體使用

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 );
}