为何Windows与Mac上Python多进程耗时比单进程更长?
问题
我知道将大型任务拆分为多个进程理论上能缩短完成时间,但我的代码没达到这个效果。测试代码如下:
from multiprocessing import Process import time import random def calculate_squares(numbers): for num in numbers: square = num * num if __name__ == "__main__": numbers = [random.randrange(1, 50, 1) for i in range(100000000)] quarter = len(numbers) // 4 first_part = numbers[:quarter] second_part = numbers[quarter:2*quarter] third_part = numbers[2*quarter:3*quarter] fourth_part = numbers[3*quarter:] start_time = time.time() # 创建四个进程 p1 = Process(target=calculate_squares, args=(first_part,)) p2 = Process(target=calculate_squares, args=(second_part,)) p3 = Process(target=calculate_squares, args=(third_part,)) p4 = Process(target=calculate_squares, args=(fourth_part,)) # 启动所有进程 p1.start() p2.start() p3.start() p4.start() # 等待所有进程完成 p1.join() p2.join() p3.join() p4.join() end_time = time.time() print(f"四进程执行时间: {(end_time - start_time) * 10**3} ms") # 单进程执行对比 start_time = time.time() calculate_squares(numbers) end_time = time.time() print(f"单进程执行时间: {(end_time - start_time) * 10**3} ms")
不同平台的运行结果:
- 13代i5(Windows平台):
Execution time with four processes: 4975.9681224823 ms Execution time for single process: 3258.450984954834 ms
- 8代i3(Linux平台):
Execution time with four processes: 1378.4070014953613 ms Execution time for single process: 2259.6046924591064 ms
- M1芯片Mac平台:
Execution time with four processes: 3175.5270957946777 ms Execution time for single process: 2120.435953140259 ms
可见Windows和Mac平台上,多进程耗时反而比单进程长,这是为什么?
原因分析
进程启动与数据拷贝开销过大:Windows和macOS默认用
spawn方式创建进程,这种方式会重新启动Python解释器、重新导入模块,还要把传递给子进程的列表数据序列化(pickle)后拷贝过去。你的代码里每个子进程要接收2500万条数据,序列化和拷贝的开销远超过多进程并行计算节省的时间。而Linux默认用fork方式,直接复制父进程内存空间,数据拷贝开销极小,所以多进程能体现优势。任务计算量太轻,开销占比过高:你的
calculate_squares只是做简单的乘法运算,属于CPU轻量任务,计算本身耗时极短。相比之下,进程创建、数据传递的开销占了总耗时的大头,导致多进程整体效率不如单进程。如果是复杂的计算密集型任务(比如大矩阵运算、加密解密),计算耗时远超过进程开销,多进程的优势才会显现。CPU架构与调度差异:M1芯片是ARM大核+小核架构,单进程可能被分配到性能更强的大核,而多进程可能被分散到小核,调度带来的额外开销抵消了并行收益。Windows平台的进程调度开销也相对更高,加上
spawn的启动成本,进一步拉低了多进程效率。无意义计算被优化:你计算出
square后没有做任何存储或输出操作,现代Python解释器和编译器会对这种无意义计算做优化,单进程下的优化可能更充分,而多进程下每个子进程的优化效果有限,额外开销盖过了优化收益。
内容的提问来源于stack exchange,提问作者Samyak Shah

