Async sleep
-
In the asynchronouse version we can see them both start and then they get to finish after waiting the appropriate time.
-
The first task took longer and thus ended after the second task.
-
One drawback of this mode of operation using
gatheris that we need to know the exact calls up-front.
import time
import asyncio
async def say(wid, sec):
start = time.monotonic()
print(f"Starting {wid} that will take {sec}s")
await asyncio.sleep(sec)
end = time.monotonic()
print(f"Finishing {wid} in {end-start}s")
async def main():
start = time.monotonic()
await asyncio.gather(
say("First", 2),
say("Second", 1)
)
end = time.monotonic()
print(f"Elapsed: {end-start}")
asyncio.run(main())
Starting First that will take 2s
Starting Second that will take 1s
Finishing Second in 1.0006165504455566s
Finishing First in 2.002072811126709s
Elapsed: 2.002306482056156