我正在运行一个程序,该程序从 REST API 发出三个不同的请求。数据、指标、请求函数都使用我制作的包装器从 BitMEX 的 api 获取数据。
我使用 asyncio 来尝试加快该过程,以便在我等待上一个请求的响应时,它可以开始发出另一个请求。
但是,由于某种原因,我的异步版本运行速度并没有更快。该代码有效,据我所知,我已正确设置所有内容。但我设置协程的方式可能有问题?
这是异步版本:
import time
import asyncio
from bordemwrapper import BitMEXData, BitMEXFunctions
'''
asynchronous I/O
'''
async def data():
data = BitMEXData().get_ohlcv(symbol='XBTUSD', timeframe='1h',
instances=25)
await asyncio.sleep(0)
return data
async def indicator():
indicator = BitMEXData().get_indicator(symbol='XBTUSD',
timeframe='1h', indicator='RSI', period=20, source='close',
instances=25)
await asyncio.sleep(0)
return indicator
async def request():
request = BitMEXFunctions().get_price()
await asyncio.sleep(0)
return request
async def chain():
data_ = await data()
indicator_ = await indicator()
request_ = await request()
return data_, indicator_, request_
async def main():
await asyncio.gather(chain())
if __name__ == '__main__':
start = time.perf_counter()
asyncio.run(main())
end = time.perf_counter()
print('process finished in {} seconds'.format(end - start))
最佳答案
不幸的是,asyncio
不是魔法。尽管您已将它们放入 async
函数,BitMEXData().get_<foo>
函数本身不是异步的(即你不能await
它们),因此在它们运行时会阻塞。 asyncio
中的并发数只能在 await
时发生正在做一些事情。
您需要一个异步发出实际 HTTP 请求的库,例如 aiohttp 。听起来你写了 bordemwrapper
你自己 - 你应该重写 get_<foo>
使用异步 HTTP 请求的函数。如果您需要帮助,请随时提交单独的问题。
关于python - 尽管等待 API 响应,但使用 asyncio 没有加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615813/