【问题标题】:Is this the right way to use multiprocessing queue with python?这是在 python 中使用多处理队列的正确方法吗?
【发布时间】:2017-06-26 04:04:19
【问题描述】:

我正在尝试通过在 Python 中使用多处理来加速我的代码。我在尝试实现多处理时遇到的唯一问题是我的函数有一个 return 语句,我需要将该数据保存到一个列表中。我发现使用谷歌的最佳方法是将队列用作“q.put()”并使用“q.get()”检索它。唯一的问题是我认为我没有以正确的方式使用它,因为当我在编译后使用命令提示符时,它表明我几乎没有使用我的 cpu,而且我只看到一个 Python 进程正在运行。如果我删除“q.get()”,这个过程会非常快并利用我的 cpu。我这样做对吗?

import time
import numpy as np
import pandas as pd
import multiprocessing 
from multiprocessing import Process, Queue


def test(x,y,q):

    q.put(x * y)


if __name__ == '__main__':

    q = Queue()

    one = []
    two = []
    three = []

    start_time = time.time()


    for x in np.arange(30, 60, 1):
        for y in np.arange(0.01, 2, 0.5):

            p = multiprocessing.Process(target=test, args=(x, y, q))
            p.start()
            one.append(q.get())
            two.append(int(x))
            three.append(float(y))
            print(x, ' | ', y, ' | ', one[-1])

    p.join()

    print("--- %s seconds ---" % (time.time() - start_time))

    d = {'x' : one, 'y': two, 'q' : three}
    data = pd.DataFrame(d)
    print(data.tail())

【问题讨论】:

    标签: python performance queue append multiprocessing


    【解决方案1】:

    不,这是不正确的。您开始一个进程并立即通过q.get 等待结果。因此只有一个进程同时运行。如果要操作很多任务,请使用multiprocessing.Pool

    import time
    import numpy as np
    from multiprocessing import Pool
    from itertools import product
    
    def test((x,y)):
        return x, y, x * y
    
    def main():
        start_time = time.time()
        pool = Pool()
        result = pool.map(test, product(np.arange(30, 60, 1), np.arange(0.01, 2, 0.5)))
        pool.close()
        print("--- %s seconds ---" % (time.time() - start_time))
        print(result)
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

    • 感谢您解决这个问题!我不明白为什么只有一个进程在运行,现在我明白了原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    相关资源
    最近更新 更多