python - 为什么在这个 python 代码中单个进程池比序列化实现更快?

标签 python multiprocessing

我正在体验 python 中的多重处理。我知道它可能比序列化计算慢,这不是我帖子的重点。

我只是想知道为什么单个进程池比我的基本问题的序列化计算更快。这些时间不应该是一样的吗?

这是代码:

import time
import multiprocessing as mp
import matplotlib.pyplot as plt


def func(x):
    return x*x*x


def multi_proc(nb_procs):
    tic = time.time()
    pool = mp.Pool(processes=nb_procs)
    pool.map_async(func, range(1, 10000000))
    toc = time.time()
    return toc-tic


def single_core():
    tic = time.time()
    [func(x) for x in range(1, 10000000)]
    toc = time.time()
    return toc-tic

if __name__ == '__main__':
    sc_times = [0]
    mc_times = [0]
    print('single core computation')
    sc_constant_time = single_core()
    print('{} secs'.format(sc_constant_time))
    for nb_procs in range(1, 12):
        print('computing for {} processes...'.format(nb_procs))
        time_elapsed = (multi_proc(nb_procs))
        print('{} secs'.format(time_elapsed))
        mc_times.append(time_elapsed)
    sc_times = [sc_constant_time for _ in mc_times]
    plt.plot(sc_times, 'r--')
    plt.plot(mc_times, 'b--')
    plt.xlabel('nb procs')
    plt.ylabel('time (s)')
    plt.show()

以及每个进程数的时间图(红色 = 串行计算,蓝色 = 多重处理): enter image description here

编辑1: 我按照 Sidhnarth Gupta 的指示修改了我的代码,这是我的新代码。我无缘无故地改变了我的功能。

import time
import multiprocessing as mp
import matplotlib.pyplot as plt
import random


def func(x):
    return random.choice(['a', 'b', 'c', 'd', 'e', 'f', 'g'])


def multi_proc(nb_procs, nb_iter):
    tic = time.time()
    pool = mp.Pool(processes=nb_procs)
    pool.map_async(func, range(1, nb_iter)).get()
    toc = time.time()
    return toc-tic


def single_core(nb_iter):
    tic = time.time()
    [func(x) for x in range(1, nb_iter)]
    toc = time.time()
    return toc-tic

if __name__ == '__main__':
    # configure
    nb_iter = 100000
    max_procs = 16
    sc_times = [0]
    mc_times = [0]

    # multi proc calls
    for nb_procs in range(1, max_procs):
        print('computing for {} processes...'.format(nb_procs))
        time_elapsed = (multi_proc(nb_procs, nb_iter))
        print('{} secs'.format(time_elapsed))
        mc_times.append(time_elapsed)

    # single proc call
    print('single core computation')
    for nb in range(1, len(mc_times)):
        print('{}...'.format(nb))
        sc_times.append(single_core(nb_iter))
    # average time
    average_time = sum(sc_times)/len(sc_times)
    print('average time on single core: {} secs'.format(average_time))

    # plot
    plt.plot(sc_times, 'r--')
    plt.plot(mc_times, 'b--')
    plt.xlabel('nb procs')
    plt.ylabel('time (s)')
    plt.show()

这是我的新情节:

enter image description here

我想我现在可以说我通过使用多处理提高了程序的速度。

最佳答案

您当前计算多处理所花费时间的代码实际上是告诉进程将任务提交到池所花费的时间。处理实际上是在异步模式下进行的,不会阻塞线程。

我尝试了您的程序并进行了以下更改:

def multi_proc(nb_procs):
    tic = time.time()
    pool = mp.Pool(processes=nb_procs)
    pool.map_async(func, range(1, 10000000)).get()
    toc = time.time()
    return toc-tic

def multi_proc(nb_procs):
    tic = time.time()
    pool = mp.Pool(processes=nb_procs)
    pool.map(func, range(1, 10000000))
    toc = time.time()
    return toc-tic

它们都比序列化计算花费更多的时间。

此外,在创建此类图表时,您还应该考虑在每次想要映射值时调用 single_core() 函数,而不是多次映射相同的值。您将看到相同时间所花费的时间存在显着差异。

关于python - 为什么在这个 python 代码中单个进程池比序列化实现更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517936/

相关文章:

python - 使用极坐标在 matplotlib 中绘制等高线密度图

python - Python中的多处理、传递多个参数以及进程之间的数据同步

Python Tornado Web 服务器 : How to use multiprocessing to speed up web application

python - 在python中使用 'multiprocessing'包的最佳实践

python - Matplotlib Pyplot 简单的意大利面条图

python - 使用 boto3 从 EFS Amazon 下载文件

python - 不应打开任何文件时 PyTorch 的数据加载器 "too many open files"错误

python多进程启动失败

python - 我如何判断 Python 的多处理模块是否正在使用我的所有内核进行计算?

python - 从 YAML 加载无限嵌套元组