【发布时间】:2020-11-16 08:08:31
【问题描述】:
我需要获取大量列表并删除“不合适”的列表。
当使用Pool.apply_async时,任务管理器声称只使用了大约 10% 的 cpu 和 97% 的内存,整个过程需要很长时间。
我对此不是很了解,但如果我使用所有内核,我觉得它应该使用超过 10% 的 cpu。
所以我的问题如下:
-
Pool.apply_sync是实现我目标的最佳方式吗?每次我想通过回调删除项目时,我都觉得回到主流程会增加太多时间/开销。 - 是什么导致了内存的过度使用?
这是我的代码示例,使用较小的列表进行演示
w_list = [[1, 0, 1], [1, 1, 0], [1, 1, 1]]
budget = 299
cost = [100, 100, 100]
def cost_interior(w):
total_cost = 0
for item in range(0, len(w)):
if w[item] == 1:
total_cost = total_cost + cost[item]
if total_cost > budget or total_cost < (0.5 * budget):
w_list.remove(w)
def remove_unfit(unfit):
if unfit is not None:
w_list.remove(unfit)
if __name__ == "__main__":
p = Pool(2)
for w in w_list:
p.apply_async(cost_interior, args=(w,), callback=remove_unfit)
p.close()
p.join()
print(w_list)
【问题讨论】:
-
如果你有一个“海量列表”,为什么会惊讶于它占用了大量内存?跨 CPU 协调工作可能会增加更多开销,而根本不会减少处理时间。
-
所以你想为庞大列表的每个元素启动一个单独的“并行”过程???不是一个很好的主意。顺便说一句:进程还是线程?
标签: python asynchronous concurrency multiprocessing pool