vis*_*ary 2 python-3.x python-asyncio
# Example 2: asynchronous requests
import asyncio
import aiohttp
import time
import concurrent.futures
no = int(input("time of per "))
num_requests = int(input("enter the no of threads "))
no_1 = no
avg = 0
async def fetch():
async with aiohttp.ClientSession() as session:
await session.get('http://google.com')
while no > 0:
start = time.time()
async def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=num_requests) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
fetch
)
for i in range(num_requests)
]
for response in await asyncio.gather(*futures):
pass
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
temp = (time.time()-start)
print(temp)
avg = avg + temp
no = no - 1
print("Average is ",avg/no_1)
Run Code Online (Sandbox Code Playgroud)
错误是RuntimeWarning:coroutine'fetch'从未等待处理句柄=无#当发生异常时需要中断周期.虽然我在fetch函数中使用await
fetch确实包含一个await,但没有人在等待fetch()自己.相反,它被调用run_in_executor,它是为同步函数设计的.虽然你当然可以像同步一样调用异步函数,但除非由协程等待或提交给事件循环,否则它将没有任何效果,并且问题中的代码都没有.
此外,不允许从不同的线程调用asyncio协程,也不必这样做.如果你需要运行像fetch()"并行" 这样的协同程序,请将它们提交到正在运行的循环中create_task()并等待它们进行大量使用gather(你已经在做了).例如:
async def main():
loop = asyncio.get_event_loop()
tasks = [loop.create_task(fetch())
for i in range(num_requests)]
for response in await asyncio.gather(*tasks):
pass # do something with response
Run Code Online (Sandbox Code Playgroud)
main() 可以在问题中调用:
loop = asyncio.get_event_loop()
while no > 0:
start = time.time()
loop.run_until_complete(main())
...
no = no - 1
Run Code Online (Sandbox Code Playgroud)
但是,为时序代码创建协程并且loop.run_until_complete()只调用一次会更加惯用:
async def avg_time():
while no > 0:
start = time.time()
await main()
...
no = no - 1
loop = asyncio.get_event_loop()
loop.run_until_complete(avg_time())
Run Code Online (Sandbox Code Playgroud)
最后,您可能希望创建ClientSessionin main或in everything并将相同的会话对象传递给每个fetch调用.会话通常在多个请求之间共享,并不意味着为每个单独的请求重新创建.
| 归档时间: |
|
| 查看次数: |
6953 次 |
| 最近记录: |