Asynchronization

asyncio

asyncio is a library to write concurrent code using the async/await syntax. asyncio is often a perfect fit for IO-bound and high-level structured network code.If your code is CPU-bound, consider using the multiprocessing library instead.

Generator, Coroutines, Event Loop

from random import randint
import time
import asyncio

def odds(start, stop):
    for odd in range(start, stop + 1, 2):
        yield odd

def randn_sync():
    """sync version"""

    # If we run this function n times,
    # then it will take 3n seconds.
    time.sleep(3)
    return randint(1, 10)

async def randn_async():
    """async version"""

    # asyncio.sleep() and randint(1, 10) will run at the same time
    await asyncio.sleep(3)
    return randint(1, 10)

async def main():

    start = time.perf_counter()
    r = await randn_async()
    elapsed = time.perf_counter() - start
    print(f"Random number generated: {r}. Took {elapsed} seconds.")

    start = time.perf_counter()
    # Generator comprehension
    r = await asyncio.gather(*(randn_async() for _ in range(10)))
    elapsed = time.perf_counter() - start
    print(f"Random number generated: {r}. Took {elapsed} seconds.")

if __name__ == '__main__':
    # Event loop
    asyncio.run(main())

Asynchronous HTTP Downloader

Reference

Async IO in Python: A Complete Walkthrough - Real Python

Last updated

Was this helpful?