CPUカウントを取得するだけでよい場合は、代わりに次psutil
を使用できます。ctypes
import ctypes
from ctypes import wintypes
class SYSTEM_INFO(ctypes.Structure):
_fields_ = [
('wProcessorArchitecture', wintypes.WORD),
('wReserved', wintypes.WORD),
('dwPageSize', wintypes.DWORD),
('lpMinimumApplicationAddress', wintypes.LPVOID),
('lpMaximumApplicationAddress', wintypes.LPVOID),
('dwActiveProcessorMask', ctypes.c_size_t),
('dwNumberOfProcessors', wintypes.DWORD),
('dwProcessorType', wintypes.DWORD),
('dwAllocationGranularity', wintypes.DWORD),
('wProcessorLevel', wintypes.WORD),
('wProcessorRevision', wintypes.WORD),
]
GetSystemInfo = ctypes.windll.kernel32.GetSystemInfo
GetSystemInfo.restype = None
GetSystemInfo.argtypes = [ctypes.POINTER(SYSTEM_INFO)]
def cpu_count():
sysinfo = SYSTEM_INFO()
GetSystemInfo(sysinfo)
num = sysinfo.dwNumberOfProcessors
if num == 0:
raise NotImplementedError('cannot determine number of cpus')
return num
編集:
NUMBER_OF_PROCESSORS
これは、環境変数と同じ値を返す可能性のある試行の代替手段です。ドキュメントにはGetSystemInfo
代わりに使用するように記載されていることに注意してください。これはpsutilが使用するものです。これもネイティブNTAPIを使用していますが、これは一般的に推奨されていません。
import ctypes
from ctypes import wintypes
SystemBasicInformation = 0
class SYSTEM_INFORMATION(ctypes.Structure): pass
PSYSTEM_INFORMATION = ctypes.POINTER(SYSTEM_INFORMATION)
class SYSTEM_BASIC_INFORMATION(SYSTEM_INFORMATION):
_fields_ = [
('Reserved1', wintypes.BYTE * 24),
('Reserved2', wintypes.LPVOID * 4),
('NumberOfProcessors', ctypes.c_ubyte),
]
ntdll = ctypes.windll.ntdll
NtQuerySystemInformation = ntdll.NtQuerySystemInformation
NtQuerySystemInformation.argtypes = [
wintypes.LONG, # SystemInformationClass
PSYSTEM_INFORMATION, # SystemInformation
wintypes.ULONG, # SystemInformationLength
wintypes.PULONG] # ReturnLength
def cpu_count():
info = SYSTEM_BASIC_INFORMATION()
retlen = wintypes.ULONG()
status = NtQuerySystemInformation(SystemBasicInformation,
info,
ctypes.sizeof(info),
retlen)
num = info.NumberOfProcessors
if status < 0 or num == 0:
raise NotImplementedError('cannot determine number of cpus')
return num