python中的异步非阻塞 async await

    技术2025-01-19  11

    from time import time, sleep """ 同步操作 """ def app01(): def fn1(): sleep(3) print("fn1 ...") def fn2(): sleep(2) print("fn2 ...") def fn3(): sleep(5) print("fn3 ...") fn1() fn2() fn3() """ asyncio """ def app02(): import asyncio async def fn1(): await asyncio.sleep(3) print("fn1 ...") async def fn2(): await asyncio.sleep(2) print("fn2 ...") async def fn3(): await asyncio.sleep(5) print("fn3 ...") loop = asyncio.get_event_loop() tasks = [ fn1(), fn2(), fn3() ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() if __name__ == '__main__': startTime = time() # app01() app02() endTime = time() print('花费了', str(endTime - startTime), '秒') # 第一个 10s # 第二个 5s
    Processed: 0.009, SQL: 9