Full answer
python
import asyncio, time
async def fetch(name, delay=0.1):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
t0 = time.perf_counter()
seq = [await fetch(n) for n in "abc"]
t_seq = time.perf_counter() - t0
t0 = time.perf_counter()
conc = await asyncio.gather(fetch("a"), fetch("b", 0.05), fetch("c"))
t_conc = time.perf_counter() - t0
print(seq)
print(conc)
print("sequential >= 0.3s:", t_seq >= 0.3, "| concurrent < 0.2s:", t_conc < 0.2)
asyncio.run(main())Output:
text
['a done', 'b done', 'c done']
['a done', 'b done', 'c done']
sequential >= 0.3s: True | concurrent < 0.2s: TrueEach fetch awaits asyncio.sleep, standing in for a network call. Run one after another, three calls take about 0.3 seconds; with gather, the waits overlap and the total is about 0.1 seconds. The run prints comparisons instead of raw times so the output is stable. gather returns results in the order of its arguments, not completion order.
Key rules:
- Calling a coroutine function does not run it; it must be awaited or scheduled (
asyncio.create_task). - Never call blocking functions such as
time.sleepor synchronous HTTP clients inside a coroutine; they freeze the whole loop. Use async libraries orasyncio.to_thread. asyncio.TaskGroup(Python 3.11+) is the structured alternative togather, cancelling sibling tasks when one fails.asyncio.run(main())starts the loop at the program's entry point.
python
import asyncio, time
async def fetch(name, delay=0.1):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
t0 = time.perf_counter()
seq = [await fetch(n) for n in "abc"]
t_seq = time.perf_counter() - t0
t0 = time.perf_counter()
conc = await asyncio.gather(fetch("a"), fetch("b", 0.05), fetch("c"))
t_conc = time.perf_counter() - t0
print(seq)
print(conc)
print("sequential >= 0.3s:", t_seq >= 0.3, "| concurrent < 0.2s:", t_conc < 0.2)
asyncio.run(main())Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- async def creates coroutines
- await yields to the event loop
- gather or TaskGroup run coroutines concurrently
- Blocking calls freeze the loop
- Results keep argument order
Common mistakes
- Calling time.sleep inside async code
- Forgetting to await a coroutine
Follow-ups
- How does TaskGroup handle errors?
- When would threads be simpler than asyncio?
Tips
- Contrast sequential and concurrent timing