带有部分参数的 map():保存 space

map() with partial arguments: save up space

我有一个非常大的字典列表,其中的键是 (stringfloatstring) 的三元组,其值也是列表。 cols_to_aggr 基本上是 list(defaultdict(list))

我希望我不仅可以将列表索引 i 传递给我的函数 _compute_aggregation,而且还可以只传递该索引包含的数据,即 cols_to_aggr[i] 而不是整个数据结构cols_to_aggr 并且必须在我的并行函数中获取较小的块。 这是因为问题是整个数据结构的这种传递导致我的池完全没有效率地耗尽了我的所有内存。

with multiprocessing.Pool(processes=n_workers, maxtasksperchild=500) as pool:
    results = pool.map(
        partial(_compute_aggregation, cols_to_aggr=cols_to_aggr,
                aggregations=aggregations, pivot_ladetag_pos=pivot_ladetag_pos,
                to_ix=to_ix), cols_to_aggr)

def _compute_aggregation(index, cols_to_aggr, aggregations, pivot_ladetag_pos, to_ix):
    data_to_process = cols_to_aggr[index]

为了解决我的内存问题,我尝试设置 maxtasksperchild 但没有成功,我不知道如何以最佳方式设置它。

使用dict.values(),您可以迭代字典的值。

因此您可以将代码更改为:

with multiprocessing.Pool(processes=n_workers, maxtasksperchild=500) as pool:
    results = pool.map(
        partial(_compute_aggregation,
                aggregations=aggregations, pivot_ladetag_pos=pivot_ladetag_pos,
                to_ix=to_ix), cols_to_aggr.values())

def _compute_aggregation(value, aggregations, pivot_ladetag_pos, to_ix):
    data_to_process = value

如果您仍然需要 _compute_aggregation 函数中的键,请改用 dict.items()