Python使用ProcessPoolExecutor容易吗?

2024-09-27 21:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

首先我使用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每次,我想知道我能做得更容易些吗?


Tags: inforreturntimedefaswithsleep
1条回答
网友
1楼 · 发布于 2024-09-27 21:33:04

您想使用Executor类的^{}方法

def s(i):
    time.sleep(1)
    return i

with ProcessPoolExecutor(max_workers=10) as executor:
    results = executor.map(s, range(WORKER_CNT))

它还有一些其他选项来控制执行的方式。你知道吗

注意results不是列表。它是一个迭代器,在计算值时接收值。所以下面的代码:

with ProcessPoolExecutor(max_workers=10) as executor:
    for result in executor.map(s, range(WORKER_CNT)):
        print(result)

一次只在内存中保存一个结果,因为它们在几秒钟内就被消耗掉,并且需要更多的时间来产生。你知道吗

相关问题 更多 >

    热门问题