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 randintimport timeimport asynciodefodds(start,stop):for odd inrange(start, stop +1, 2):yield odddefrandn_sync():"""sync version"""# If we run this function n times,# then it will take 3n seconds. time.sleep(3)returnrandint(1, 10)asyncdefrandn_async():"""async version"""# asyncio.sleep() and randint(1, 10) will run at the same timeawait asyncio.sleep(3)returnrandint(1, 10)asyncdefmain(): start = time.perf_counter() r =awaitrandn_async() elapsed = time.perf_counter()- startprint(f"Random number generated: {r}. Took {elapsed} seconds.") start = time.perf_counter()# Generator comprehension r =await asyncio.gather(*(randn_async() for _ inrange(10))) elapsed = time.perf_counter()- startprint(f"Random number generated: {r}. Took {elapsed} seconds.")if__name__=='__main__':# Event loop asyncio.run(main())