我有两个不同的函数(
funcA
和funcB
),我想同时执行它们以减少总体执行时间。
funcA
是一个 API 调用,需要 5 到 7 秒的时间。
funcB
是一种 CPU 密集型操作,使用 ML 算法,需要 7 到 10 秒的时间。
这一切都将在 python 服务器上完成。
请求将包含两部分,比如说
inpA
和 inpB
。 inpA
将传递至 funcA
,inpB
将传递至 funcB
。
目前整体执行情况如下:
def processRequest(request):
response = {}
response['outA'] = funcA(request['inpA'])
response['outB'] = funcB(request['inpB'])
return response
因此,整个执行过程大约需要 12 到 17 秒。 但考虑到这两个函数都采用单独的输入并且彼此不依赖,如果它们可以同时执行,则总体请求将花费更少的时间(本示例为 7 到 10 秒)。
正在使用的每个功能都是同步的。我可以使
funcA
异步,但现在无法选择使 funcB
异步。也许它可以封装在 async
函数中。我不太确定 Python 中的异步编程,因此我们将不胜感激。也许multithreading
也可以是一个选择。
我尝试使用
asyncio
库和它的收集功能。但由于某种原因,它的工作原理与上面描述的 processRequest
功能相同。
您可以使用 Python 的
ThreadPoolExecutor
模块中的
concurrent.futures
。我为你的问题写了一个简单的演示:
from concurrent.futures import ThreadPoolExecutor
import time
from time import sleep
def funcA(x):
sleep(7) # simulate a long running task
return x * x
def funcB(y):
sleep(10) # simulate a long running task
return y + y
# the global executor
executor = ThreadPoolExecutor(max_workers=2)
def main(x, y):
res = []
start = time.time()
# submit the tasks
task_A = executor.submit(funcA, x)
task_B = executor.submit(funcB, y)
# wait for the tasks to complete
res.append(task_A.result())
res.append(task_B.result())
end = time.time()
print("Time taken: {}".format(end - start))
return res
if __name__ == '__main__':
print(main(2, 3))
输出:
Time taken: 10.005340814590454
[4, 6]
完成 7 秒的任务 A 和 10 秒的任务 B 需要约 10 秒。