【问题标题】:Parallel processing taking longer than serial processing & skipping to process few entries并行处理比串行处理花费更长的时间并跳过处理少量条目
【发布时间】: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


【解决方案1】:

在多处理中,您还需要考虑创建进程的开销。在此示例中,每个进程都在执行一项非常小的任务,即打印一条语句。因此,开销 将非常重要,这就是为什么您会得到这样的结果。

CPU 密集型(计算繁重)任务中建议使用多处理。但是,这里 不是 的情况。因此,您应该在其他示例中尝试一下。

【讨论】:

  • 我在函数中添加了_i = i ** 100000 行,我可以看到并行比串行快很多。谢谢大家的建议!
猜你喜欢
  • 2013-11-09
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 2017-01-27
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多