首先我使用ProcessPoolExecutor
如下:
def s(i):
time.sleep(1)
return i
futs = []
with ProcessPoolExecutor(max_workers=10) as executor:
for i in range(WORKER_CNT):
print executor.submit(s, i,).result()
但我发现这是不平行的,然后我换成这样:
def s(i):
time.sleep(1)
return i
futs = []
with ProcessPoolExecutor(max_workers=10) as executor:
for i in range(WORKER_CNT):
futs.append(executor.submit(s, i,))
for f in futs:
print f.result()
然后我开始担心WORKER_CNT
可能太大,我需要等待很长时间才能看到最后的结果,所以我改为:
def s(i):
time.sleep(1)
return i
futs = []
with ProcessPoolExecutor(max_workers=10) as executor:
for i in range(WORKER_CNT):
futs.append(executor.submit(s, i,))
if len(futs) == 10:
for f in futs:
print f.result()
futs = []
这一次,我可以处理10
每次,我想知道我能做得更容易些吗?
您想使用} 方法:
Executor
类的^{它还有一些其他选项来控制执行的方式。你知道吗
注意
results
不是列表。它是一个迭代器,在计算值时接收值。所以下面的代码:一次只在内存中保存一个结果,因为它们在几秒钟内就被消耗掉,并且需要更多的时间来产生。你知道吗
相关问题 更多 >
编程相关推荐