Python 为什么通过共享内存进行的通信比通过队列进行的通信慢得多?

Python 为什么通过共享内存进行的通信比通过队列进行的通信慢得多?,python,performance,multiprocessing,message-queue,shared-memory,Python,Performance,Multiprocessing,Message Queue,Shared Memory,我在最近的老式苹果MacBookPro上使用Python2.7.5,它有四个硬件和八个逻辑CPU;i、 例如,sysctl实用程序提供: $ sysctl hw.physicalcpu hw.physicalcpu: 4 $ sysctl hw.logicalcpu hw.logicalcpu: 8 我需要对一个大的1-D列表或数组执行一些相当复杂的处理,然后将结果保存为中间输出,稍后在我的应用程序中的后续计算中再次使用。我的问题的结构非常自然地适合并行化,所以我想我会尝试使用Python的多

我在最近的老式苹果MacBookPro上使用Python2.7.5,它有四个硬件和八个逻辑CPU;i、 例如,sysctl实用程序提供:

$ sysctl hw.physicalcpu
hw.physicalcpu: 4
$ sysctl hw.logicalcpu
hw.logicalcpu: 8
我需要对一个大的1-D列表或数组执行一些相当复杂的处理,然后将结果保存为中间输出,稍后在我的应用程序中的后续计算中再次使用。我的问题的结构非常自然地适合并行化,所以我想我会尝试使用Python的多处理模块将1D数组细分为几个部分(4个部分或8个部分,我还不确定是哪一个),并行执行计算,然后将生成的输出重新组装为最终格式。我正试图决定是使用
多处理.Queue()
(消息队列)还是
多处理.Array()
(共享内存)作为我的首选机制,将结果计算从子进程传输回主父进程,我一直在试验两个“玩具”模型,以确保我了解多处理模块的实际工作方式。然而,我遇到了一个意想不到的结果:在为同一个问题创建两个本质上等价的解决方案时,使用共享内存进行进程间通信的版本似乎比使用消息队列的版本需要更多的执行时间(大约30倍)。下面,我为一个“玩具”问题提供了两个不同版本的示例源代码,该问题使用并行进程生成一个长的随机数序列,并以两种不同的方式将聚合结果传回父进程:第一次使用消息队列,第二次使用共享内存

以下是使用消息队列的版本:

import random
import multiprocessing
import datetime

def genRandom(count, id, q):

    print("Now starting process {0}".format(id))
    output = []
    # Generate a list of random numbers, of length "count"
    for i in xrange(count):
        output.append(random.random())
    # Write the output to a queue, to be read by the calling process 
    q.put(output)

if __name__ == "__main__":
    # Number of random numbers to be generated by each process
    size = 1000000
    # Number of processes to create -- the total size of all of the random
    # numbers generated will ultimately be (procs * size)
    procs = 4

    # Create a list of jobs and queues 
    jobs = []
    outqs = []
    for i in xrange(0, procs):
        q = multiprocessing.Queue()
        p = multiprocessing.Process(target=genRandom, args=(size, i, q))
        jobs.append(p)
        outqs.append(q)

    # Start time of the parallel processing and communications section
    tstart = datetime.datetime.now()    
    # Start the processes (i.e. calculate the random number lists)      
    for j in jobs:
        j.start()

    # Read out the data from the queues
    data = []
    for q in outqs:
        data.extend(q.get())

    # Ensure all of the processes have finished
    for j in jobs:
        j.join()
    # End time of the parallel processing and communications section
    tstop = datetime.datetime.now()
    tdelta = datetime.timedelta.total_seconds(tstop - tstart)

    msg = "{0} random numbers generated in {1} seconds"
    print(msg.format(len(data), tdelta))
当我运行它时,我得到的结果通常如下所示:

$ python multiproc_queue.py
Now starting process 0
Now starting process 1
Now starting process 2
Now starting process 3
4000000 random numbers generated in 0.514805 seconds
$ python multiproc_shmem.py 
Now starting process 0
Now starting process 1
Now starting process 2
Now starting process 3
4000000 random numbers generated in 15.839607 seconds
现在,这里是等效的代码段,但只是稍微进行了重构,以便使用共享内存而不是队列:

import random
import multiprocessing
import datetime

def genRandom(count, id, d):

    print("Now starting process {0}".format(id))
    # Generate a list of random numbers, of length "count", and write them
    # directly to a segment of an array in shared memory
    for i in xrange(count*id, count*(id+1)):
        d[i] = random.random()

if __name__ == "__main__":
    # Number of random numbers to be generated by each process
    size = 1000000
    # Number of processes to create -- the total size of all of the random
    # numbers generated will ultimately be (procs * size)
    procs = 4

    # Create a list of jobs and a block of shared memory
    jobs = []
    data = multiprocessing.Array('d', size*procs)
    for i in xrange(0, procs):
        p = multiprocessing.Process(target=genRandom, args=(size, i, data))
        jobs.append(p)

    # Start time of the parallel processing and communications section
    tstart = datetime.datetime.now()    
    # 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()
    # End time of the parallel processing and communications section
    tstop = datetime.datetime.now()
    tdelta = datetime.timedelta.total_seconds(tstop - tstart)

    msg = "{0} random numbers generated in {1} seconds"
    print(msg.format(len(data), tdelta))
然而,当我运行共享内存版本时,典型的结果看起来更像这样:

$ python multiproc_queue.py
Now starting process 0
Now starting process 1
Now starting process 2
Now starting process 3
4000000 random numbers generated in 0.514805 seconds
$ python multiproc_shmem.py 
Now starting process 0
Now starting process 1
Now starting process 2
Now starting process 3
4000000 random numbers generated in 15.839607 seconds

我的问题:为什么我的代码的两个版本在执行速度上有如此巨大的差异(大约0.5秒与15秒,是30倍!)?特别是,如何修改共享内存版本以使其运行更快?

这是因为
多处理。默认情况下,数组使用锁来防止多个进程同时访问它:

多处理.Array(类型代码\u或类型、大小\u或\u初始值设定项,*, 锁定=真)

如果lock为True(默认值),则将创建一个新的lock对象以同步对该值的访问。如果lock是lock或RLock对象 然后,将使用该值同步访问。如果锁是 False则不会自动访问返回的对象 由锁保护,因此它不一定是“过程安全的”

这意味着您实际上并没有并发地写入数组-一次只有一个进程可以访问它。由于您的示例工作人员除了数组写入之外几乎什么都不做,因此持续等待此锁会严重影响性能。如果在创建阵列时使用
lock=False
,性能会更好:

lock=True时

Now starting process 0
Now starting process 1
Now starting process 2
Now starting process 3
4000000 random numbers generated in 4.811205 seconds
如果
lock=False

Now starting process 0
Now starting process 3
Now starting process 1
Now starting process 2
4000000 random numbers generated in 0.192473 seconds

请注意,使用
lock=False
意味着您需要在执行进程不安全的操作时手动保护对
数组的访问。您的示例是让流程写入唯一的部分,所以这没关系。但是,如果你试图在这样做的时候读它,或者有不同的进程写到重叠的部分,你需要手动获取一个锁。

移动你的<代码>队列。在<代码>的第一个例子中,把放进< /COR> >循环,与第二个例子中的<代码> d[i] < /代码>相符合。目前,您无法比较这两种技术,因为
队列
一种是批量使用的,而共享内存一种是热切使用的。谢谢!一百万年来,我从未想到是内存锁定导致了所有额外的开销。