python - 使用多处理时避免重新编译 numba 代码

标签 python multiprocessing numba

我一直在使用 numba 进行多重处理。

唯一的问题 - numba 分别为每个进程重新编译代码。

(当进程数等于物理CPU数时,问题不大, 但当情况并非如此时,这是一个巨大的数字!)

有没有办法让numba编译一次代码, 然后跨进程边界共享编译的工件?

示例 -

from multiprocessing import Process
from time import time, sleep
from numba import njit


@njit
def child():
    pass


if __name__ == "__main__":
    ps = [Process(target=child) for _ in range(100)]
    for p in ps:
        p.start()
    s = time()
    for p in ps:
        p.join()
    print("compile time:", time() - s)
compile time: 19.10037922859192

所有核心的 CPU 使用率均固定为 100%。 我已经尝试过 numba 的 cache=True,但不幸的是我的代码无法缓存。

/Users/dev/PycharmProjects/trading/tradingdo/strategy.py:91: NumbaWarning: Cannot cache compiled function "_strategy1" as it uses dynamic globals (such as ctypes pointers and large global arrays)
  @njit

最佳答案

在支持 fork() 的系统 (Linux) 上,这很容易 -

只需在启动进程之前编译该函数一次 - 这将使 numba 缓存编译器输出,就像通常一样。

但是由于 fork 的写时复制魔法,该缓存会自动与子进程共享!

不太清楚的是如何在没有适当 fork() 支持的系统上执行此操作。 numba 的缓存可以 pickled 吗?

from multiprocessing import Process
from time import time, sleep
from numba import njit


@njit
def child():
    pass


if __name__ == "__main__":
    child() # this will do it

    ps = [Process(target=child) for _ in range(100)]
    for p in ps:
        p.start()
    s = time()
    for p in ps:
        p.join()
    print("compile time:", time() - s)

compile time: 0.011722326278686523

numba 的 nogil 也值得一看。 。这可以消除对进程的需要,并且线程共享 numba 编译缓存就可以了

关于python - 使用多处理时避免重新编译 numba 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63875749/

相关文章:

python - 清理从 Flask MethodView API 启动的长时间运行的子进程

python - 如何在 python 中生成具有特定长度的任意字符串?

python - 为运行多处理队列的 python 脚本激活内存不足 killer ?

windows - 等待程序的最后一个实例

python - 如何将附加参数传递给 numba cfunc 作为 LowLevelCallable 传递给 scipy.integrate.quad

python - 如何加速分析 NumPy 代码 - 矢量化,Numba?

python - 从 txt 文件读取到 3 个不同列表时如何防止硬编码 - python

python - 子类化时如何不必在 init 中键入 self

python - Python 的 `list(some_dictionary)` 是线程安全的吗?

python - Numba jitted len() 比纯 Python len() 慢