我需要使用 asyncio 并行發送請求。請求是通過server_time我無法更改的庫中的函式發送的。它是一個函式,而不是協程,所以不能等待它,這就是這里的挑戰。
我一直在嘗試使用下面的代碼,但它顯然不起作用,同樣的原因你可以并行化await asyncio.sleep(1)但不能并行化time.sleep(1)。
我如何使用 asyncio 來并行化它?即,我怎樣才能并行化time.sleep(1)使用 asyncio 之類的東西?
from pybit import HTTP
import time
import asyncio
session = HTTP('https://api-testnet.bybit.com')
async def latency():
time_1 = time.perf_counter()
session.server_time()
return time.perf_counter() - time_1
async def avg_latency(n_requests):
total_time = 0
tasks = []
for _ in range(n_requests):
tasks.append(asyncio.create_task(latency()))
for task in tasks:
total_time = await task
return total_time / n_requests
# First one to establish the connection. The latency improves after.
session.server_time()
latency = asyncio.run(avg_latency(10))
print(f'{1000 * latency:.2f} ms')
uj5u.com熱心網友回復:
您可以使用它來并行run_in_executor運行同步的 I/O 系結函式:session.server_time
import asyncio
from pybit import HTTP
import time
session = HTTP('https://api-testnet.bybit.com')
async def latency():
time_1 = time.perf_counter()
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, session.server_time)
return time.perf_counter() - time_1
async def avg_latency(n_requests):
return sum(await asyncio.gather(*[latency() for _ in range(n_requests)]))/n_requests
print(asyncior.run(avg_latency(10)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442728.html
