Roughly how long does main() take?
import asyncio
async def main():
await asyncio.sleep(1)
await asyncio.sleep(1)
await asyncio.sleep(1)
asyncio.run(main())Options
- ~1 second
- ~3 seconds (Correct option)
- ~0 seconds
- It never finishes
Answer
~3 seconds
Why
await means: wait here until this finishes, then continue to the next line.
The three sleeps therefore run one after another: 1 + 1 + 1 = 3 seconds.
To run them at the same time, start them together with asyncio.gather; then they wait in parallel and the total is about 1 second.
await asyncio.gather(
asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)
) # ~1 secondRemember
Separate awaits run in sequence; gather runs them concurrently.