gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:55:00 30 4
gpt4 key购买 nike

我一直在使用 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 的缓存可以腌制吗?

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com