在Windows下统计进程的CPU使用率

在网上查了一下,基本上都使用GetSystemTimes函数来取得当前CPU时间的,但是这个函数要到Windows XP SP1才有,在之前版本的Windows下无法使用。

上网搜了一下老外的文章,发现内部函数NtQuerySystemInformation可以取得当前CPU时间,而且各NT版本通用。

以下是我写的一个显示CPU使用率的代码:

#include 
#include 
#include 
#define MAKE_INT64( l, h ) ( ((INT64)(h)<<32) | (l) )

int main()
{
	SYSTEM_INFO SystemInfo;
	GetSystemInfo( &SystemInfo );
	UINT32 nProcessorCount = SystemInfo.dwNumberOfProcessors; // CPU数量

	NTSTATUS (WINAPI *pNtQuerySystemInformation)(
		_In_       SYSTEM_INFORMATION_CLASS SystemInformationClass,
		_Inout_    PVOID SystemInformation,
		_In_       ULONG SystemInformationLength,
		_Out_opt_  PULONG ReturnLength
		);

	HMODULE hNtDll = LoadLibraryA( "ntdll.dll" );
	if( hNtDll == NULL ) return printf( "LoadLibraryA: %s\n", GetOsErrorMessageA().c_str() );

	pNtQuerySystemInformation = (NTSTATUS (WINAPI *)( SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG ))GetProcAddress( hNtDll, "NtQuerySystemInformation" );
	if( pNtQuerySystemInformation == NULL ) return printf( "GetProcAddress: %s\n", GetOsErrorMessageA().c_str() );

	INT64 nLastSystemTime = 0; // 最近一次取得的系统CPU时间
	INT64 nLastIdleTime = 0; // 最近一次取得的CPU空闲时间
	INT64 nLastProcessTime = 0; // 最近一次取得的进程CPU时间
	while( 1 )
	{
		FILETIME CreationTime, ExitTime, KernelTime, UserTime;
		GetProcessTimes( GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime );
		INT64 nCurProcessTime = MAKE_INT64( KernelTime.dwLowDateTime, KernelTime.dwHighDateTime ) + MAKE_INT64( UserTime.dwLowDateTime, UserTime.dwHighDateTime );

		SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION Info;
		ULONG nOut;
		pNtQuerySystemInformation( SystemProcessorPerformanceInformation, &Info, sizeof(Info), &nOut );
		if( nLastSystemTime > 0 )
		{
			printf( "ststem=%0.2f%%, process=%0.2f%%\n"
				// 计算前后CPU空闲时间差值在系统CPU时间差值中的比例得到系统CPU空闲率
				, 100 - (Info.IdleTime.QuadPart - nLastIdleTime) / (double)(Info.KernelTime.QuadPart + Info.UserTime.QuadPart - nLastSystemTime) * 100
				// 计算前后进程CPU时间差值在系统CPU时间差值中的比例得到进程CPU使用率(一个CPU是100)
				,(nCurProcessTime - nLastProcessTime) / (double)(Info.KernelTime.QuadPart + Info.UserTime.QuadPart - nLastSystemTime) * 100 / nProcessorCount
				);
		}
		nLastSystemTime = Info.KernelTime.QuadPart+Info.UserTime.QuadPart;
		nLastIdleTime = Info.IdleTime.QuadPart;
		nLastProcessTime = nCurProcessTime;

		SLEEP(1000);
	}

	return 0;
}


你可能感兴趣的:(在Windows下统计进程的CPU使用率)