我希望使用多处理
来加速缓慢的循环。然而,从我所看到的多处理示例来看,我不确定这种实现是否是良好的实践、可行或可能。
循环大致分为两个部分:数据摄取
和数据处理
。我希望在处理过程中开始数据摄取的下一部分,以便数据尽快可用。
伪代码:
d = get_data(n)
for n in range(N):
p = process_data(d)
d = get_data(n+1) #prepare data for next process loop
- 多重处理适合这种功能吗?
- 如何做到这一点?
提前致谢。
最佳答案
正如您所说,多处理基本上是调度和收集工作。
正如您所澄清的,您基本上希望 process_data
和 get_data
并行工作。
这是我为您提供的解决方案
import multiprocessing as mp
# create pool for dispatching work
pool = mp.Pool()
# call your functions asynchronously
process_data_process = pool.apply_async(process_data, (d,))
get_data_process = pool.apply_async(get_data, (n+1,))
# After your functions are dispatched, wait for results
process_data_result = process_data_process.get()
get_data_result = get_data_process.get()
# Note: get_data_result will not be fetched till process_data_result is ready
# But that should be fine since you can't start the next batch
# till this batch is done
你可以将其包装在你的循环中。 希望这能回答您的问题!
关于Python 多处理循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778842/