想试试服务器的并行计算能力,就让cpu慢慢计算,计算0~n之间所有素数之和
设置target为结尾,num_of_processors为进程数,即可开始跑
如下所示
from multiprocessing import Pool import math import numpy import time def isPrime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def f(data): start,end = data result = 0 for n in range(start,end+1): if isPrime(n): result += n return result def main(): num_of_processors = 12 target = 10000000 data = numpy.linspace(0, target, num_of_processors+1).astype(int) start_time = time.time() pool = Pool(num_of_processors) result = pool.map(f, list(zip(data[:-1],data[1:])) ) pool.close() pool.join() print("总耗时",time.time() - start_time) print(f"0~{target}的素数之和:",sum(result)) if __name__ == "__main__": main()
结果:
标签:python,demo,素数,并行计算,之间,import From: https://www.cnblogs.com/youmuchen/p/17223698.html