陈景润证明-多进程

时间:2024-11-12 08:51:48
from multiprocessing.pool import Pool
import time
import math
t = time.time()
c = 4
p = Pool(c)
seplist = [100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000]
result = p.map(Goldbach, seplist)
print(result)
p.close()
p.join()
print("multi processing time cost:" + "%d" %(time.time() - t))
time2 = time.time()
for a in seplist: Goldbach(a)
print("single processing time cost:" + "%d" %(time.time() - time2))

进程池设为4,映射map里用的函数是单进程的Goldbach。

对比

[(100000, 11, 99989), (200000, 67, 199933), (300000, 7, 299993), (400000, 11, 399989), (500000, 31, 499969), (600000, 7, 599993), (700000, 47, 699953), (800000, 7, 799993), (900000, 19, 899981)]
multi processing time cost:8
100000 = 11 + 99989
200000 = 67 + 199933
300000 = 7 + 299993
400000 = 11 + 399989
500000 = 31 + 499969
600000 = 7 + 599993
700000 = 47 + 699953
800000 = 7 + 799993
900000 = 19 + 899981
single processing time cost:28

从输出结果看进程池的方法少用了二十秒。

注意点

多进程调用Goldbach的时候,print(“%d = %d + %d”%(i, j, k))这行打印没有打印出来。只好把它们作为返回值打印出来。