正如MichaelButscher在评论中所说,这是一种特殊的行为
sleep
. 对于CPU密集型任务,我看到好处是有限的,进程数等于核心数。
def f(x):
out = 0
for i in range(5000000):
out += i
return x*x
def execute_time(processes):
t1 = datetime.now()
with Pool(processes) as p:
p.map(f, list(range(36)))
t2 = datetime.now()
return t2 - t1
for p in range(1, 25):
t = execute_time(p)
print(p, ":", t)
得到:
# 1 : 0:00:13.329320
# 2 : 0:00:07.528552
# 3 : 0:00:09.943043
# 4 : 0:00:07.756005
# 5 : 0:00:08.262304
# 6 : 0:00:07.653659
# 7 : 0:00:07.677038
# 8 : 0:00:07.591766
# 9 : 0:00:07.502283
# 10 : 0:00:07.710826
# 11 : 0:00:06.006874
# 12 : 0:00:09.720279
# 13 : 0:00:07.912836
# 14 : 0:00:07.616807
# 15 : 0:00:07.740225
# 16 : 0:00:07.721783
# 17 : 0:00:07.836259
# 18 : 0:00:07.665993
# 19 : 0:00:07.564645
# 20 : 0:00:07.653607
# 21 : 0:00:07.754377
# 22 : 0:00:07.886036
# 23 : 0:00:11.696323
# 24 : 0:00:07.674243