根据这个问题和答案-- Python multiprocessing.cpu_count() returns '1' on 4-core Nvidia Jetson TK1 --某些系统上的multiprocessing.cpu_count()
函数的输出反映了当前正在使用的CPU数量,而不是调用Python程序实际可用的CPU数量。
一种常见的Python习惯用法是使用cpu_count()
的返回值来初始化Pool
中的进程数量。然而,在使用这种“动态CPU激活”策略的系统上,这个习惯用法就会被破坏得相当严重(至少在相对静止的系统上是这样)。
有没有什么直接的(和可移植的)方法可以从中获得可用的处理器的数量(与当前正在使用的数量相反)?
备注:
/proc/self/status
的内容显示所有4个内核都可供程序使用。在我看来,/proc/self/status
内容的方法,它的格式在不同的版本之间可能会有所不同,甚至在OS X上也不存在。(任何其他伪文件也是如此)。
发布于 2019-08-05 16:40:37
使用psutil:
从文档https://psutil.readthedocs.io/en/latest/
>>> import psutil
>>> psutil.cpu_count()
4
>>> psutil.cpu_count(logical=False) # Ignoring virtual cores
2
这是便携的
发布于 2021-09-15 23:35:33
以下是一种获取当前进程可用CPU核心数量的方法,这些进程位于实现sched_getaffinity
和Windows的系统上:
import ctypes
import ctypes.wintypes
import os
from platform import system
def num_available_cores() -> int:
if hasattr(os, 'sched_getaffinity'):
return len(os.sched_getaffinity(0))
elif system() == 'Windows':
kernel32 = ctypes.WinDLL('kernel32')
DWORD_PTR = ctypes.wintypes.WPARAM
PDWORD_PTR = ctypes.POINTER(DWORD_PTR)
GetCurrentProcess = kernel32.GetCurrentProcess
GetCurrentProcess.restype = ctypes.wintypes.HANDLE
GetProcessAffinityMask = kernel32.GetProcessAffinityMask
GetProcessAffinityMask.argtypes = (ctypes.wintypes.HANDLE, PDWORD_PTR, PDWORD_PTR)
mask = DWORD_PTR()
if not GetProcessAffinityMask(GetCurrentProcess(), ctypes.byref(mask), ctypes.byref(DWORD_PTR())):
raise Exception("Call to 'GetProcessAffinityMask' failed")
return bin(mask.value).count('1')
else:
raise Exception('Cannot determine the number of available cores')
在Linux和任何其他实现sched_getaffinity
的系统上,我们都使用Python的内置包装器。
在Windows上,我们使用ctypes
来调用GetProcessAffinityMask
。
据我所知,在macOS上没有用户API或工具来获取/设置CPU亲和性。在大多数情况下,os.cpu_count()
可以很好地工作,但如果您确实需要可用内核的数量,那么您可能就不走运了。
https://stackoverflow.com/questions/31346974
复制相似问题