GetLogicalProcessorInformation

最近在看《windows核心编程》,看到如何获得处理器信息,不是太明白,下面是获得处理器核心数的代码,我自己加了一些注释。

//获得处理器核心数
 void ShowProcessors()
 {
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pBuffer = NULL;
DWORD dwSize = 0;
DWORD procCoreCount;

//获得有dwSize的大小
BOOL bResult = GetLogicalProcessorInformation(pBuffer, &dwSize);
if(GetLastError() != ERROR_INSUFFICIENT_BUFFER){
	_tprintf(TEXT("Impossible to get processor information\n"));
	return;
}

//获得SYSTEM_LOGICAL_PROCESSOR_INFORMATION数组,数组中包含了所有逻辑处理器信息
pBuffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(dwSize);
bResult = GetLogicalProcessorInformation(pBuffer, &dwSize);
if(!bResult){
	free(pBuffer);
	_tprintf(TEXT("Impossible to get processor information\n"));
	return;
}

procCoreCount = 0;
//逻辑处理器数量
DWORD lpiCount = dwSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
for(DWORD current = 0; current < lpiCount; current++){
	//逻辑处理器的Relationship为RelationProcessorCore,表示该逻辑处理器是处理器核心
	if(pBuffer[current].Relationship == RelationProcessorCore){
		//该标志表示处理器的用途
		if(pBuffer[current].ProcessorCore.Flags == 1){
			_tprintf(TEXT(" + one CPU core (HyperThreading)\n"));
		} else {
			_tprintf(TEXT("+ one CPU socket\n"));
		}
		procCoreCount++;

	}
}
_tprintf(TEXT("-> %d active CPU(s) \n"), procCoreCount);

free(pBuffer);
 }

一开始不懂为什么要调用两次GetLogicalProcessorInformation函数,后来查了一下msdn,得知第一次是获得系统有多少个逻辑处理器数,也就是需要传递多大的SYSTEM_LOGICAL_PROCESSOR_INFORMATION数组给GetLogicalProcessorInformation函数,第二次调用的时候,函数会给pBuffer数组赋值。下面是MSDN上给出的关于函数的注解:

函数原型: BOOL WINAPI GetLogicalProcessorInformation( Out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, Inout PDWORD ReturnLength );

Buffer [out] A pointer to a buffer that receives an array of SYSTEM_LOGICAL_PROCESSOR_INFORMATION structures. If the function fails, the contents of this buffer are undefined.

ReturnLength [in, out] On input, specifies the length of the buffer pointed to by Buffer, in bytes. If the buffer is large enough to contain all of the data, this function succeeds and ReturnLength is set to the number of bytes returned. If the buffer is not large enough to contain all of the data, the function fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and ReturnLength is set to the buffer length required to contain all of the data. If the function fails with an error other than ERROR_INSUFFICIENT_BUFFER, the value of ReturnLength is undefined.

参考: http://blog.csdn.net/zyl910/article/details/7547264

转载于:https://my.oschina.net/u/168794/blog/173106

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值