我正在尝试在python中构建多处理以降低计算速度,但似乎在多处理之后,整体计算速度显着下降。我创建了4个不同的进程,并将dataFrame拆分为4个不同的数据帧,这些数据帧将作为每个进程的输入。在对每个流程进行计时后,似乎开销成本很高,并且想知道是否有办法降低这些管理费用。
我使用的是windows7,python 3.5,我的机器有8个核心。
def doSomething(args, dataPassed,):
processing data, and calculating outputs
def parallelize_dataframe(df, nestedApply):
df_split = np.array_split(df, 4)
pool = multiprocessing.Pool(4)
df = pool.map(nestedApply, df_split)
print ('finished with Simulation')
time = float((dt.datetime.now() - startTime).total_seconds())
pool.close()
pool.join()
def nestedApply(df):
func2 = partial(doSomething, args=())
res = df.apply(func2, axis=1)
res = [output Tables]
return res
if __name__ == '__main__':
data = pd.read_sql_query(query, conn)
parallelize_dataframe(data, nestedApply)
答案 0 :(得分:1)
我建议使用队列而不是将DataFrame作为块提供。你需要大量的资源来复制每个块,这需要相当长的时间才能完成。如果你的DataFrame非常大,你可能会耗尽内存。使用队列可以从pandas中的快速迭代器中受益。
这是我的方法。开销随着工人的复杂性而降低。不幸的是,我的工作人员很难真正证明这一点,但sleep
模拟了复杂性。
import pandas as pd
import multiprocessing as mp
import numpy as np
import time
def worker(in_queue, out_queue):
for row in iter(in_queue.get, 'STOP'):
value = (row[1] * row[2] / row[3]) + row[4]
time.sleep(0.1)
out_queue.put((row[0], value))
if __name__ == "__main__":
# fill a DataFrame
df = pd.DataFrame(np.random.randn(1e5, 4), columns=list('ABCD'))
in_queue = mp.Queue()
out_queue = mp.Queue()
# setup workers
numProc = 2
process = [mp.Process(target=worker,
args=(in_queue, out_queue)) for x in range(numProc)]
# run processes
for p in process:
p.start()
# iterator over rows
it = df.itertuples()
# fill queue and get data
# code fills the queue until a new element is available in the output
# fill blocks if no slot is available in the in_queue
for i in range(len(df)):
while out_queue.empty():
# fill the queue
try:
row = next(it)
in_queue.put((row[0], row[1], row[2], row[3], row[4]), block=True) # row = (index, A, B, C, D) tuple
except StopIteration:
break
row_data = out_queue.get()
df.loc[row_data[0], "Result"] = row_data[1]
# signals for processes stop
for p in process:
in_queue.put('STOP')
# wait for processes to finish
for p in process:
p.join()
使用numProc = 2
每个循环需要50秒,numProc = 4
速度是其两倍。