Coroutines are the foundation of Python, and python has greatly improved its execution efficiency because of them. Coroutines association word with the meaning of collaboration, assuming that in the case of only one thread, we want to run multiple function, normal process is a next to a run, but the efficiency is too low, a very simple example, if have three functions, the first function to run for 3 minutes, the second function run for 2 minutes, the third run 1 minute. So it takes 6 minutes to run, but it takes 3 minutes to run with coroutines, because you maximise, you don’t have to sum. If the function here is not CPU intensive, but a function that requires very little computing resources, but is time-consuming, for example, network requests, network requests are very common, in fact, we don’t need a lot of computing resources on the computer, and we spend a lot of time waiting, So if we can work together in between waiting periods, we can use this thread to compute other functions. Let’s look at a very simple example:

Import time import asyncio async def eat(): await asyncio.sleep(3) print(' eat ') async def sleep(): Await asyncio.sleep(2) print(' sleep ') async def dadoudou(): Get_event_loop () Tasks = asyncio.Gather (eat(),sleep(),dadoudou()) start=time.time() loop.run_until_complete(tasks) print('total spend time is {:.2f}s'.format(time.time()-start)) loop.close()Copy the code

The results are as follows:

Total spend time is 3.00sCopy the code

We can see that our program ends in 3 seconds instead of 6 seconds, so that’s the beauty of coroutines, how does it work? The function asyncio.Gather (eat(),sleep(),dadoudou())) is used to wrap the program. This function is not just wrapping, but also the internal process task scheduling. When it finds three AWIAT keywords, it can know that it needs to run three coroutines. Run_until_complete (Tasks) and the application will run directly and run all three await simultaneously so that we can do asynchronous computation. This example is very simple, we can look at an example diagram:

We can see that with coroutines you only need to find the maximum computation time as the total running time of the program, and not using coroutines is the sum, so 3 seconds with coroutines, 6 seconds without coroutines.

But note that coroutines does not improve the efficiency of the CPU, in both the IO intensive and cpu-intensive, coroutines essence is to improve, just improve program waiting for time to use, and compared with the threads and coroutines directly switch much faster, otherwise this stuff than directly using threads, thread in Python switching efficiency is very low, So you need something like coroutines in place of some usage scenarios.