【问题标题】:Using Python's multiprocessing.Pool(), am I really doing multi-processing?使用 Python 的 multiprocessing.Pool(),我真的在做多处理吗?
【发布时间】:2019-11-17 02:20:46
【问题描述】:

我目前正在研究 '''multiprocessing''' 包。这是我在 '''multiprocessing.Process''' 和 '''multiprocessing.Pool''' 上尝试的简单代码。

import random
import multiprocessing
import time


def list_append(count, id, out_list):
    """
    Creates an empty list and then appends a 
    random number to the list 'count' number
    of times. A CPU-heavy operation!
    """
    for i in range(count):
        out_list.append(random.random())


if __name__ == "__main__":
    size = 10000000   # Number of random numbers to add
    procs = 8   # Number of processes to create

    # Create a list of jobs and then iterate through
    # the number of processes appending each process to
    # the job list 

    print('number of CPU: ', multiprocessing.cpu_count())

    starting = time.time()
    jobs = []
    for i in range(procs):
        out_list = list()
        process = multiprocessing.Process(target=list_append, 
                                          args=(size, i, out_list))
        jobs.append(process)

    # Start the processes (i.e. calculate the random number lists)      
    for j in jobs:
        j.start()

    # Ensure all of the processes have finished
    for j in jobs:
        j.join()

    print("jobs one done in {}".format(time.time()-starting))

    starting = time.time()
    for i in range(procs):
        p = multiprocessing.Pool(8)
        p.starmap(list_append, [(size, i, list())])

    print('jobs two done in {}'.format(time.time()-starting))

我的笔记本电脑有 12 个杯芯,所以我希望工作一和工作二能在相似的时间内完成。但是,作业一在 3 秒内完成,而作业二在 12 秒内完成。在我看来,'''multiprocessing.Pool()''' 实际上并没有做多进程......我做错了什么吗?

【问题讨论】:

    标签: python multiprocessing


    【解决方案1】:

    在你的第二个工作中,你没有使用多处理。 starmap() 将指定的方法 (list_append) 分配给第二个参数中提供的每个 arg 列表,但您只提供一个包含一个元素的列表,因此您的 for 循环的每次迭代都会执行一个过程。我想你打算这样做:

    p = multiprocessing.Pool(8)
    p.starmap(list_append, [(size, i, list()) for i in range(procs)])
    

    不包含 for 循环。

    还要注意,starmap 等待结果,所以在 for 循环中,它等待每个单独的进程。

    【讨论】:

    • 啊。谢谢先生。明白了。还有一个问题,我可以写出星图的循环吗?我可能会有乘法循环......例如,for i in range(),for size in range()
    • 您可以在任何地方创建 args 列表,然后只需在 starmap 调用中引用该列表。它只需要是一个iterable,每个元素都是要传递给list_append(或任何你的真实方法)调用的参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2013-08-13
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    相关资源
    最近更新 更多