【发布时间】:2020-07-29 00:42:31
【问题描述】:
为什么 Python 中的并行处理比串行处理慢?
#!/usr/bin/env python3
import os
import time
from functools import partial
import multiprocessing as mp
def print_hello(i, typ):
print(typ + " : PID-" + str(os.getpid()) + "\n")
# print("Hello World " + str(i))
if __name__ == '__main__':
N= mp.cpu_count()
parallel_start_time = time.time()
with mp.Pool(processes = N) as p:
p.map(partial(print_hello,typ="Parallel"), (x for x in range(100)))
parallel_end_time = time.time()
serial_start_time = time.time()
for x in range(100):
print_hello(x, "Serial")
serial_end_time = time.time()
print("Parallel processing took " + str(parallel_end_time - parallel_start_time) + " seconds")
print("Serial processing took " + str(serial_end_time - serial_start_time) + " seconds")
我将上述脚本的输出写入一个文本文件,下面是最终输出
./test_parallel.py > pid.txt
61 Parallel : PID-28311 Parallel processing took 0.11675715446472168 seconds 100 Serial : PID-28310 Serial processing took 0.0001430511474609375 seconds
我也不明白为什么python在使用并行处理时没有处理39个id
【问题讨论】:
-
子进程不能保证以任何特定顺序运行,因此在您的示例中,并行进程 62-100 的打印行实际上很有可能高于第 61 个进程的打印行。
-
在
print(typ + " : PID-" + str(os.getpid()) + "\n")前加个疯狂的东西,比如_ = 11 ** 100000,并行会更快。 -
在对并行处理进行基准测试时,请确保进行一些实际处理。仅添加
p.map(partial(的函数调用就意味着“并行”版本的工作量是在实际运行任何东西之前的三倍。由于有效负载实际上什么都不做,因此开销非常大。 -
当我运行你的代码时,所有 100 个并行和串行处理都会发生。后者的缓慢是由于创建额外的 Python 解释器任务的开销。
-
@KacperFloriański:你的建议有效!
标签: python python-3.x