python

时间:2017-04-14 08:49:03

标签: python asynchronous multiprocess

我正在尝试在给定数据集中应用具有两个相邻元素的特定函数。请参考以下示例。

# I'll just make a simple function here.
# In my real case, I send request to database 
# to get the result with two arguments.

def get_data_from_db_with(arg1, arg2):
    # write a query with arg1 and arg2 named 'query_result'
    return query_result

data = [arg1, arg2, arg3, arg4]
result = []
for a, b in zip(data, data[1:]):
    result.append(get_data_from_db_with(a, b))

例如,如果数据长度为4,如上所示,那么我向数据库发送请求3次。每个请求大约需要0.3秒来检索数据,因此总共需要0.9秒(0.3秒* 3个请求)。问题是随着请求数量的增加,总体时间也会增加。我想做的是,如果可能的话,立即发送所有请求。基本上,它看起来像这样。

使用上面的代码,

1) get_data_from_db_with(arg1, arg2)
2) get_data_from_db_with(arg2, arg3)
3) get_data_from_db_with(arg3, arg4)

将连续处理。

如果可能,我想要做的是一次性发送请求,而不是连续发送请求。当然,请求数量保持不变。但根据我的假设,总体时间消耗将减少。

现在我正在寻找异步,多处理等等。 任何评论或反馈都会非常有用。

提前致谢。

2 个答案:

答案 0 :(得分:2)

线程可能就是你要找的东西。假设大多数作业get_data_from_db_with都在等待i / o,比如调用数据库。

import threading

def get_data_from_db_with(arg1, arg2):
    # write a query with arg1 and arg2 named 'query_result'
    current_thread = threading.current_thread()
    current_thread.result = query_result

data = [arg1, arg2, arg3, arg4]
threads = []
for a, b in zip(data, data[1:]):
    t = threading.Thread(target=get_data_from_db_with, args=(a,b))
    t.start()
    threads.append(t)

results = []
for t in threads:
    t.join()
    results.append(t.result)

请注意,此解决方案甚至会保留results列表中的订单。

答案 1 :(得分:1)

多处理的替代方法是处理查询构造本身。寻找将(arg1 and arg2) or (arg2 and arg3)...之类的查询组合在一起的方法,实质上是尝试在一次调用中获取所有必需的数据。

相关问题