python多进程 获取返回值的简单示例

例子参照了 https://docs.python.org/3/library/concurrent.futures.html

import math
import time
from concurrent.futures import ProcessPoolExecutor

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n == 2:
        return True
    if n < 2 or n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    start = time.time()
    with ProcessPoolExecutor(max_workers=len(PRIMES)) as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))
    cost = time.time() - start
    print(f'Done. Cost: {cost:.2f} seconds')

if __name__ == '__main__':
    main()

max_workers 用于指定同时运行的进程数, 网上有说要设成CPU数量, 不过实测是不同的函数,不同的机器,有不同的最佳值, 有时设到100反而更佳.

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页