Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Count Async

import time
import asyncio

async def count(name, end, sec):
    for i in range(end):
        print(f"{name} {i}")
        await asyncio.sleep(sec)

async def main():
    await asyncio.gather(
        count('apple', 10, 0.1),
        count('peach', 10, 0.2),
        )

start = time.time()
asyncio.run(main())
end = time.time()
print(f"Elapsed {end-start}")
apple 0
peach 0
apple 1
peach 1
apple 2
apple 3
peach 2
apple 4
apple 5
peach 3
apple 6
apple 7
peach 4
apple 8
apple 9
peach 5
peach 6
peach 7
peach 8
peach 9
Elapsed 2.010511636734009