Python 正在停止使用pool.apply\u async()生成的进程,然后再将其完成

Python 正在停止使用pool.apply\u async()生成的进程,然后再将其完成,python,Python,假设我们使用pool.apply\u async()生成了一些进程。当任何一个进程返回值时,如何停止所有其他进程? 另外,这是获得算法运行时间的正确方法吗? 以下是示例代码:- import timeit import multiprocessing as mp data = range(1,200000) def func(search): for val in data: if val >= search: # Doing somet

假设我们使用pool.apply\u async()生成了一些进程。当任何一个进程返回值时,如何停止所有其他进程? 另外,这是获得算法运行时间的正确方法吗? 以下是示例代码:-

import timeit
import multiprocessing as mp

data = range(1,200000)

def func(search):
    for val in data:
        if val >= search:
            # Doing something such that other processes stop ????
            return val*val 

if __name__ == "__main__":
    cpu_count = mp.cpu_count()
    pool = mp.Pool(processes = cpu_count)

    output = []

    start = timeit.default_timer()

    results = []
    while cpu_count >= 1:
        results.append(pool.apply_async(func, (150000,)))
        cpu_count = cpu_count - 1

    output = [p.get() for p in results]
    stop = timeit.default_timer()
    print output

    pool.close()
    pool.join()

    print "Running Time : " + str(stop - start) + " seconds"

我从来没有这样做过,但是python文档似乎给出了一个如何做的想法

参考:

在您的代码片段中,我会这样做:

while cpu_count >= 1:
        if len(results)>0:
            pool.terminate()
            pool.close()
            break
        results.append(pool.apply_async(func, (150000,)))
        cpu_count = cpu_count - 1

而且你的计时方法似乎还可以。我会在开始和停止时使用
time.time()
,然后显示减法,因为我已经习惯了。

我从来没有这样做过,但python文档似乎给出了一个如何做的想法

参考:

在您的代码片段中,我会这样做:

while cpu_count >= 1:
        if len(results)>0:
            pool.terminate()
            pool.close()
            break
        results.append(pool.apply_async(func, (150000,)))
        cpu_count = cpu_count - 1
而且你的计时方法似乎还可以。我会在开始和停止时使用
time.time()
,然后显示减法,因为我已经习惯了