为什么在多处理Python中,工人比处理器多会提高运行时间?
我正在使用python作为理解一些使用多处理的简单实现的手段。然而,我遇到了一个非常意外的结果。在开始之前,以下是我的系统详细信息:为什么在多处理Python中,工人比处理器多会提高运行时间?,python,multithreading,performance,multiprocessing,cpu-speed,Python,Multithreading,Performance,Multiprocessing,Cpu Speed,我正在使用python作为理解一些使用多处理的简单实现的手段。然而,我遇到了一个非常意外的结果。在开始之前,以下是我的系统详细信息: 计算机类型:带Windows 10的笔记本电脑Ram:8.00 GBCPU:Intel(R)Core(TM)i7-6600U@2.60GHz基本速度:2.80 GHz插槽:1内核:2逻辑处理器:4一级缓存:128KB二级缓存:512KB三级缓存:4.0MB 取下列几何级数计算n数的平均值: 考虑到这个想法,我创建了一个函数,用于计算下限a(包含)和上限b(排除
n
数的平均值:
考虑到这个想法,我创建了一个函数,用于计算下限a
(包含)和上限b
(排除)之间整数的平均值。然后,我在5亿个整数的范围内运行一个带有和不带多处理的测试:
import time
import concurrent.futures
def mean(a, b):
total_sum = 0
for next_int in range(a, b):
total_sum += next_int
return total_sum / (b - a)
if __name__ == '__main__':
n = 500000000 # 500 Million
wall_time = time.time()
base_ans = mean(0, n) # From 0 to n-1.
print("Single Thread Time: " + str(time.time() - wall_time) + " sec.")
work = [(0, int(n/2)), (int(n/2), n)]
num_workers = 2 # One process per core!
test_ans = 0
wall_time = time.time()
with concurrent.futures.ProcessPoolExecutor(max_workers=num_workers) as executor:
future_tasks = {executor.submit(mean, job[0], job[1]): job for job in work}
for future in concurrent.futures.as_completed(future_tasks):
test_ans += future.result()
print("Multiprocessing Time: " + str(time.time() - wall_time) + " sec.")
print(str(base_ans) + " == " + str(test_ans / num_workers) + " => " + str(base_ans == (test_ans / num_workers)))
以下操作生成以下输出:
Single Thread Time: 41.0769419670105 sec. # CPU Utilization ≈ 35% (from task manager)
Multiprocessing Time: 24.71605634689331 sec. # CPU Utilization ≈ 70% (from task manager)
我们可以清楚地看到,观察到一个主要的加速(大约1.66x)。但是,如果我创建4个工人,而不是2个工人,我会获得更高的速度:
work = [(0, int(n/4)), (int(n/4), int(n/2)), (int(n/2), int(3*n/4)), (int(3*n/4), n)]
num_workers = 4
# ...
Single Thread Time: 41.51883292198181 sec. # CPU Utilization ≈ 35% (from task manager)
Multiprocessing Time: 18.18532919883728 sec. # CPU Utilization = 100% (from task manager)
在这里可以看到更大的速度提升(大约2.28x),甚至可以在多次跑步中看到
max\u worker
编号?在物理核心计数之后,我应该再添加多少个进程您意识到逻辑处理器在许多情况下确实提供了实际的加速,对吗?当然,增益没有那么大,但它不是零(在理想情况下高达30%)。他们不只是做出了决定。这个答案可能是相关的