kkamegawa's weblog

Visual Studio,TFS,ALM,VSTS,DevOps関係のことについていろいろと書いていきます。Google Analyticsで解析を行っています

プログラムから論理プロセッサ数を取得する

会社でちょっと話題に出たので。
普通プロセッサ数がほしければ、GetSystemInfo()を使用すればプロセッサ数もとれるので、まぁこれで十分でしょう。ただ、プロセッサライセンスなどで論理プロセッサの数を知りたいというニーズはそこはかとなくたまに聞こえます。
ちなみにIntel CPUの論理プロセッサ元祖であるHyper Threadでは、EAXをCPUID命令を発行して、EDXレジスタの28bit目が1だったらHyper Threadが有効なのだそうです。
Shudo's Notes (2001/12)
もっとお手軽に…という向きでは、WMIが思いつきます。Win32_Processorクラスにそれらしいものがあります。ところが…

NumberOfLogicalProcessors
Data type: uint32
Access type: Read-only
Number of logical processors for the current instance of the processor. For processors capable of hyperthreading, this value includes only the processors which have hyperthreading enabled. For more information, see Remarks.

Windows Server 2003, Windows XP, and Windows 2000: This property is not available.

orz。試してみたところ、Windows Server 2003 R2ではだめでした。Windows Vista SP1ではこのページにも載っているVBScriptで正しく取得できます。

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colCompSys = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
For Each objCS in colCompSys
  WScript.Echo "  NumberOfProcessors: " & objCS.NumberOfProcessors
  WScript.Echo "  NumberOfLogicalProcessors: " & objCS.NumberOfLogicalProcessors
  WScript.Echo "  PCSystemType: " & objCS.PCSystemType
Next

複数物理プロセッサを積んだWindows Server 2008とかないので、これ以上検証はできませんが。で、これを調べているときに気づいたサポートページ。Live SearchはWin32_Processorクラスのページがトップに出てこなくて面白いものをひっかけますね。
The Win32_Processor class returns the incorrect Name property for the processors on a computer that is running Windows XP or Windows Server 2003 and the computer has Intel Core 2 Duo processors installed
Win32_Processor WMI クラスのファミリ属性は Windows Server 2003 ベースのコンピューター上で実行する一部のプロセッサの不適切な値が返されます
KB924779のほうはWindows Server 2003 SP2で修正されているんだそうです。