我正在运行一个大型比较,但在比较完成后,大约25%的总运行时间用于清理deque。我的代码看起来像这样:
from collections import deque
from multiprocessing import Pool
from _map_workflow import val_comp
if __name__ == '__main__':
pool = Pool()
records = deque(pool.imap_unordered(val_comp, combinations(index_tups,2)))
for _ in range(records.count(None)):
records.remove(None)
比较函数val_comp
仅在满足某些条件时返回值,但在不返回任何值时,deque会加载None
。由于我是使用imap
的多处理程序,我不确定如何过滤添加到deque中的内容。
有没有一种更快/更有效的方法来删除这些None
或从一开始就阻止它们添加?
.remove
是deque
对象的O(N(运算。
所以,总的来说,如果有M无,你就有O(M*N(行为。
这是完全可以避免的。一个简单的方法是使用filter
:
records = deque(filter(None, pool.imap_unordered(val_comp, combinations(index_tups,2))))
如果你想在你已经有了records
数据后过滤掉它们,你可以做一些类似的事情:
records = deque(x for x in records if x is not None)
这创建了一个新的CCD_ 9。