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

本文介绍了如何在Windows操作系统下,尤其是XP SP1之前的版本,通过内部函数NtQuerySystemInformation来统计和获取进程的CPU使用率,替代了通常使用的GetSystemTimes函数。

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

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

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

#include <windows.h>
#include <Winternl.h>
#include <stdio.h>
#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;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值