【发布时间】: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