使用python线程同时执行慢速sql

2024-04-19 15:53:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常慢的存储过程(每次运行约30分钟),它为传递的每个日期写入输出表。唯一的参数是输入日期,它需要在一个范围内每天运行。使用游标或for循环不会导致加速,因为它是按顺序运行的,并且每次运行过程都必须等待前一次运行完成。你知道吗

我已经尝试使用线程来执行一个范围内的每个日期的进程,但是我没有注意到预期的加速。如果我做错了什么,或者是否有一种更普遍接受的方式来运行并发SQL,请告诉我。我预计,由于一次执行需要30分钟,如果我同时运行过程,那么100个日期所需的时间应该比一次执行所需的30分钟稍长,但绝对不是线性增长。你知道吗

以下是代码的相关部分:

def query(table_name,prod_dt):
    cur.execute("exec {} '{}';".format(table_name,prod_dt))
    conn.commit()

def next_workday(start_date,end_date):
    start_date=datetime.strptime(start_date,'%Y-%m-%d')
    end_date=datetime.strptime(end_date,'%Y-%m-%d')
    yield datetime.strftime(start_date,'%Y-%m-%d')
    while start_date<end_date:
        start_date+=BDay(1)
        yield datetime.strftime(start_date+BDay(0),'%Y-%m-%d')

def main():
    ''' 
    change func call in line 1 to last_workday_of_month or next_workday
    depending on what you need, monthly vs daily business days
    '''
    for date in next_workday('2014-12-31','2015-03-31'):
        t1=Thread(target=query,args=('slow_proc',date))
        t1.start()
        t1.join()

Tags: namefordatetimedate过程defdttable