You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS系统下os.sched_getaffinity的替代方案有哪些?

macOS下替代os.sched_getaffinity的内置方案

Python官方文档中,os.cpu_count()的说明里推荐使用len(os.sched_getaffinity(0))来获取当前进程可使用的CPU核心数,但在macOS系统中调用该方法会触发如下错误:

>>> len(os.sched_getaffinity(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'os' has no attribute 'sched_getaffinity'

根据Python调度器接口的文档说明:

它们仅在部分Unix平台可用。

针对macOS系统,优先推荐内置解决方案如下:

你的临时方案(推荐使用)

你当前的实现已经是很合理的跨平台方案,通过异常捕获机制,在os.sched_getaffinity不可用时回退到multiprocessing.cpu_count():

import multiprocessing
import os

def _get_core_count() -> int:
    try:
        # 仅部分Unix平台可用
        return len(os.sched_getaffinity(0))  # type: ignore[attr-defined]
    except AttributeError:
        return multiprocessing.cpu_count()

这个方案的优势在于:

  • 优先使用更准确的os.sched_getaffinity(能反映进程实际被分配的CPU核心数,而非系统总核心数)
  • 跨平台兼容性好,macOS、Windows等不支持os.sched_getaffinity的系统会自动回退到通用实现

其他内置备选方案

如果不需要区分"进程可用核心数"和"系统总核心数",也可以直接使用os.cpu_count(),它在macOS上能正常返回系统的总CPU核心数:

import os

def get_core_count() -> int:
    return os.cpu_count() or 1  # 兜底避免返回None

但注意os.cpu_count()返回的是系统总核心数,无法体现进程被限制的CPU亲和性(如果有)。


内容的提问来源于stack exchange,提问作者Intrastellar Explorer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:05:18