import asyncio
import time
async def foo():
await asyncio.sleep(3)
async def bar():
await asyncio.sleep(4)
"""
测试时间:3 + 4 = 7秒, 注意await就是直接阻塞了,此时如果是web后台在处理客户端请求的时候会阻塞当前线程后面的处理,但是会空闲时间去处理其他的请求,所以并发性会大大提高
"""
async def exec():
begin_time = time.time()
await foo()
await bar()
print("一共花费的时间为: ", int(time.time() - begin_time), '秒')
"""
测试时间:最长的时间 4s,所以并发的异步请求只有这么设置才会并发处理任务
"""
async def exec2():
task1 = asyncio.create_task(foo())
task2 = asyncio.create_task(bar())
begin_time = time.time()
await task1
await task2
print("一共花费的时间为: ", int(time.time() - begin_time), '秒')
if __name__ == '__main__':
asyncio.run(exec()) # 一共花费的时间为: 7 秒
asyncio.run(exec2()) # 一共花费的时间为: 4 秒