示例工程 18-asyncio-event-loop

18-asyncio-event-loop/01-serial-vs-gather/serial_vs_gather.py

python · 1.0 KB

"""对比串行 await 与 asyncio.gather 的耗时。"""
 
from __future__ import annotations
 
import asyncio
import time
 
 
async def work(name: str, delay: float = 0.05) -> str:
    await asyncio.sleep(delay)
    return name
 
 
async def serial() -> tuple[list[str], float]:
    started = time.perf_counter()
    results = [await work("a"), await work("b"), await work("c")]
    return results, time.perf_counter() - started
 
 
async def concurrent() -> tuple[list[str], float]:
    started = time.perf_counter()
    results = await asyncio.gather(work("a"), work("b"), work("c"))
    return list(results), time.perf_counter() - started
 
 
async def main() -> None:
    serial_results, serial_time = await serial()
    gather_results, gather_time = await concurrent()
    print(f"serial: {serial_results} {serial_time:.2f}s")
    print(f"gather: {gather_results} {gather_time:.2f}s")
    print(f"speedup: {serial_time / gather_time:.1f}x")
 
 
if __name__ == "__main__":
    asyncio.run(main())