我编写了一个简单的python多处理程序,其中它从csv中读取一堆行,调用api,然后写入新的csv中。但是,我看到的是该程序的性能与顺序执行相同。更改池大小没有任何效果。怎么了?
from multiprocessing import Pool
from random import randint
from time import sleep
import csv
import requests
import json
def orders_v4(order_number):
response = requests.request("GET", url, headers=headers, params=querystring, verify=False)
return response.json()
newcsvFile=open('gom_acr_status.csv', 'w')
writer = csv.writer(newcsvFile)
def process_line(row):
ol_key = row['\ufeffORDER_LINE_KEY']
order_number=row['ORDER_NUMBER']
orders_json = orders_v4(order_number)
oms_order_key = orders_json['oms_order_key']
order_lines = orders_json["order_lines"]
for order_line in order_lines:
if ol_key==order_line['order_line_key']:
print(order_number)
print(ol_key)
ftype = order_line['fulfillment_spec']['fulfillment_type']
status_desc = order_line['statuses'][0]['status_description']
print(ftype)
print(status_desc)
listrow = [ol_key, order_number, ftype, status_desc]
#(writer)
writer.writerow(listrow)
newcsvFile.flush()
def get_next_line():
with open("gom_acr.csv", 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
yield row
f = get_next_line()
t = Pool(processes=50)
for i in f:
t.map(process_line, (i,))
t.join()
t.close()
答案 0 :(得分:2)
编辑:我刚刚注意到您在循环中调用map
。您只需调用一次即可。是一个 blocking 函数,它不是异步的!查看the docs以获得正确用法的示例。
与map()内置函数的并行等效项(尽管它仅支持一个可迭代的参数)。 它会阻塞直到结果准备就绪。
原始答案:
所有进程都写入输出文件这一事实导致文件系统争用。
如果您的process_line
函数仅返回行(例如,作为字符串列表),那么主进程将在map
全部返回之后写入所有这些行,那么您应该体验一下性能增强。
也有2个注释: