【发布时间】:2018-04-20 02:41:38
【问题描述】:
我正在学习将池与多处理一起使用。我做了这个脚本作为练习。
谁能告诉我为什么使用普通的 for 循环比使用池花费的时间更少?
P.S:我的 CPU 有 2 个核心。
非常感谢。
from multiprocessing import Pool
from functools import reduce
import time
def one(n):
a = n*n
return a
if __name__ == '__main__':
l = list(range(1000))
p = Pool()
t = time.time()
pol = p.map(one, l)
result = reduce(lambda x,y: x+y, pol)
print("Using Pool the result is: ", result, "Time: ", time.time() - t )
p.close()
p.join()
def two(n):
t = time.time()
p_result = []
for i in n:
a = i*i
p_result.append(a)
result = reduce(lambda x,y: x+y, p_result)
print("Not using Pool the result is: ", result, "Time: ", time.time() - t)
two(l)
使用 Pool 结果为: 332833500 时间: 0.14810872077941895
不使用 Pool 结果是: 332833500 时间: 0.0005018711090087891
【问题讨论】:
标签: python-3.x multiprocessing pool