使用Python的ProcessPool时出现意外表现

2024-05-14 06:18:07 发布

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

我正在尝试使用Python中的ProcessPoolExecutorconcurrent.futures包。但是,我的表现很差 我不明白为什么。你知道吗

我的代码如下所示:

import time
from itertools import product
from concurrent.futures import ProcessPoolExecutor

def myfunc(bundle):
    "A simple function which takes some time to complete."
    clock_start = time.clock()
    for _ in range(*bundle):
        lst = [[0., 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1.0]
                for x in range(6)]
        res = [t for t in product(*lst) if abs(sum(t) - 1.) < 1e-8]
    clock_elapsed = time.clock() - clock_start
    return clock_elapsed

def parallel(bundles, nworkers):
    "A function to dispatch execution between different workers."
    with ProcessPoolExecutor(max_workers=nworkers) as executor:
        execgen = executor.map(myfunc, bundles)
        total_clock = 0.
        for _clock in execgen:
            total_clock += _clock
    print("mean iteration: {:.3f} s".format(total_clock / bundles[-1][-1]))

(函数myfunc本身没有兴趣,但我希望 执行在迭代次数上是线性的)。你知道吗

当我在我的计算机(python3.6,Debian,8cpu)上测试这段代码时,我 得到以下结果:

>>> parallel([(0, 60)], 1)
mean iteration: 3.660 s

>>> parallel([(0, 30), (30, 60)], 2)
mean iteration: 3.747 s

>>> parallel([(0, 20), (20, 40), (40, 60)], 3)
mean iteration: 4.413 s

>>> parallel([(0, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 60)], 6)
mean iteration: 7.534 s

所以,很明显,把死刑分为6名工人意味着 一次迭代的平均时间是一次迭代的两倍 工人。因为迭代应该是完全独立的,所以我不能 弄明白为什么会这样吗?你知道吗


Tags: 代码inimportfortimeparallelmyfuncmean
1条回答
网友
1楼 · 发布于 2024-05-14 06:18:07

你的代码与你的动机不符。在所有4次代码运行中,无论使用多少核,总时钟始终是完成整个60次计算的时间总和。理论上,所有4次运行都应该返回相同的值,而不考虑多进程成本(通信…)。显然,这取决于实际的计算工作量,而不管它在哪里(哪个核心)运行。你知道吗

我相信你想证明多进程是时间效率。更新代码

print("mean iteration: {:.3f} s".format(total_clock / nworkers)) 

或者只是用人类的直觉去感觉和比较这4次跑步回来之前经过的时间。你知道吗

相关问题 更多 >