【发布时间】:2020-07-03 06:04:41
【问题描述】:
我想在 python 中使用带有生成器函数的多处理
假设我有大量列表big_list,我想使用多处理来计算值。如果我使用返回值的“传统”函数,这很简单:
import concurrent
def compute_function(list_of_lists):
return_values = [] ## empty list
for list in list_of_lists:
new_value = compute_something(list) ## compute something; just an example
return_values.append(new_value) ## append to list
return return_values
with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
new_list = list(executor.map(compute_function, big_list))
但是,以这种方式使用列表会占用大量内存。所以我想改用生成器函数:
import concurrent
def generator_function(list_of_lists):
for list in list_of_lists:
new_value = compute_something(list) ## compute something; just an example
yield new_value
with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
new_list = list(executor.map(generator_function, big_list))
我的问题是,你不能腌制生成器。对于其他数据结构,有一些解决此问题的方法,但我认为不适用于生成器。
我怎样才能做到这一点?
【问题讨论】:
-
您能否为此提供更多背景信息?可能有更好的方法来提高性能。
-
@AMC 我试图避免使用大型列表,因为它们无法放入内存。有关更多上下文,我在这里有一个类似的问题:stackoverflow.com/questions/60798407/…
-
@AMC 我会说,我正在处理的基本问题是如何使用多处理而不是在 RAM 中爆炸。这本质上是我的问题,而我目前拥有的数据结构是一个列表字典——这有意义吗?
-
如果在生成结果时循环遍历结果,是否仍会占用大量内存?您是否稍后以减少内存消耗的方式转换结果,程序的其余部分是否设置为这样工作?
-
"如果在结果生成时循环遍历结果,是否仍然太占用内存?"这不会比使用多处理慢得多吗?
标签: python parallel-processing multiprocessing bigdata generator