Python 3 on macOS:如何设置进程关联

Python 3 on macOS: how to set process affinity

我正在尝试限制 Python 使用的 CPU 数量(用于基准测试并查看它是否加快了我的程序)。

我找到了几个 Python 模块来实现这个('os'、'affinity'、'psutil')除了它们改变亲和力的方法只适用于 Linux(有时 Windows)。还有一个建议使用 'taskset' 命令 (Why does multiprocessing use only a single core after I import numpy?),但据我所知,此命令在 macOS 上不可用。

在 macOS 上 运行 Python / iPython 时,是否有一种(最好是干净简单的)方法来更改亲和力?似乎在 Mac 中更改处理器关联并不像在其他平台 (http://softwareramblings.com/2008/04/thread-affinity-on-os-x.html) 中那么容易。

不可能。见 Thread Affinity API Release Notes:

OS X does not export interfaces that identify processors or control thread placement—explicit thread to processor binding is not supported. Instead, the kernel manages all thread placement. Applications expect that the scheduler will, under most circumstances, run its threads using a good processor placement with respect to cache affinity.

请注意,线程亲和性是您在优化程序时考虑得相当晚的事情,有一百万件事情要做,而这些事情对您的程序影响更大。

另请注意,Python 一开始在多线程方面特别糟糕。