为什么Python ThreadPoolExecutor.map与ProcesspPlexecutor相比要花这么长时间才能产生结果?
以这个程序为例:为什么Python ThreadPoolExecutor.map与ProcesspPlexecutor相比要花这么长时间才能产生结果?,python,generator,python-multithreading,Python,Generator,Python Multithreading,以这个程序为例: from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def fun(xx): for _ in range(10): y = 1 x = xx while x > 0: y = (y * x) % 1000000007 x -= 1 print("END {}! = {}
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def fun(xx):
for _ in range(10):
y = 1
x = xx
while x > 0:
y = (y * x) % 1000000007
x -= 1
print("END {}! = {}".format(xx, y))
return xx, y
with ThreadPoolExecutor(max_workers=8) as executor:
out = executor.map(fun, range(10000))
for x in out:
print(x)
这使我能够在每次实际计算函数时以及在输出生成器中读取输出时看到打印的消息。当生成器运行时,应该期望函数消息不会严格有序。此外,我希望生成器“作为管道”向我提供数据,在处理整个输入之前为我提供中间结果。这可能是我正在处理的无限流
如果我使用ProcessPoolExecutor
,它的工作原理与我预期的一样,我很快就可以在线程池创建新结果时开始从输出生成器读取数据。另一方面,使用ThreadPoolExecutor
,虽然它似乎工作得很好,但它只是在大量函数执行之后才开始向我提供输出。例如:
END 6363! = 280520285
END 6364! = 231081245
END 6365! = 832114135
END 6366! = 238546331
(0, 1)
(1, 1)
(2, 2)
(3, 6)
(4, 24)
END 6368! = 281286418
END 6369! = 513183705
END 6370! = 980177974
为什么会有如此巨大的差异,我如何控制这种行为?如果我想使用线程,并且我想确保更快地得到结果,我是否应该自己分块数据,而不是依赖于
map
?在ProcessPoolExecutor中获得更快结果的一个原因是它生成迭代器的块,因此每个块都分配给cpu的核心(分配的工作人员数量)该内核可能更快地完成其块的计算,并且可以进一步执行for循环