gpt4 book ai didi

python - 在 python 中一次执行多项任务

转载 作者:行者123 更新时间:2023-11-28 22:28:44 25 4
gpt4 key购买 nike

我正在尝试对给定数据集中的两个相邻元素应用特定函数。请引用下面的例子。

# 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)

将被连续处理。


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

现在我正在搜索异步、多处理等。任何评论或反馈都会非常有帮助。

提前致谢。

最佳答案

Threads 可能就是您正在寻找的。假设 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 列表中的顺序。

关于python - 在 python 中一次执行多项任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43408235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com