import math
import datetime
import multiprocessing as mp
def f(x, y):
for i in range(10000000):
pass
return x+y
if __name__ == '__main__':
param_dict = zip(list(range(100)), list(range(100)))
print(param_dict)
start_t = datetime.datetime.now()
results1=[]
for x, y in param_dict:
results1.append(f(x, y))
print(results1)
end_t = datetime.datetime.now()
elapsed_sec = (end_t - start_t).total_seconds()
print("單进程计算 共消耗: " + "{:.2f}".format(elapsed_sec) + " 秒")
start_t = datetime.datetime.now()
num_cores = int(mp.cpu_count())
print("本地计算机有: " + str(num_cores) + " 核心")
pool = mp.Pool(num_cores)
param_dict = zip(list(range(100)), list(range(100)))
print(param_dict)
results2 = [pool.apply_async(f, args=(x,y)) for x,y in param_dict]
results2 = [p.get() for p in results2]
print(results2)
end_t = datetime.datetime.now()
elapsed_sec = (end_t - start_t).total_seconds()
print("多进程计算 共消耗: " + "{:.2f}".format(elapsed_sec) + " 秒")
result: