Async IO in Python

The topic of this tutorial is: Async IO in Python.

Introduction: Asyncio is a Python library which is completely different from parallelism. It helps to write, execute and compile our code. Basically we call IO tasks which can’t perform bu CPU or takes a lot of time compare with CPU power and speed. For example, suppose you are running on a treadmill, and your shoe lase is not tied what will happen? Definitely you will fall down. The same thing applies to our CPU. Suppose you are having a really heavy page and you want to load it but there is an image and one server is not working which is connected to that image. What will happen? The whole web page will get disturbed which will consume a lot of time. So, one solution of both shoe problem is to keep your shoelace tie and run. Same with webpage problem where Asyncio makes this task easy because other things can load without that image. So the final conclusion is it uses a single thread and single core of CPU which is quite confusing in itself.

Before starting first let us understand the difference between synchronous code and asynchronous code,

Synchronous code:

It is the code you are probably writing right now. Means you are writing one function then another function and running it one bu one. It is the default method of writing any program and we are doing it from the beginning.

Asynchronous code:

Here you are running multiple functions parallelly. So it is an example of that condition which we discussed earlier in this blog about a man who is running on a treadmill. But it requires some really well-behaving functions and also there is no space for blocking functions.

Let us see the coding part, Here I am writing the same code for both the conditions.

Synchronous code in Python:

import time
def even(x):
    for i in range(x-1,0,-1):
        if i%2==0:
            print(i)
            break
        time.sleep(0.01)
        
def main():
    even(100000)
    even(10000)
    even(1000)
    
main()

Output:

99998
9998
998

Asynchronous code in Python:

import time
import asyncio
def even(x):
    for i in range(x-1,0,-1):
        if i%2==0:
            print(i)
            break
        await asyncio.sleep(0.01)
    return None
        
async def main():
    await asyncio.wait([
        even(100000),
        even(10000),
        even(1000),
    ])
    
func = asyncio.get_event_loop()
func.run_until_complete(main())
loop.close()

Output: Same as the previous one

Conclusion: Both the methods are correct at their position but if we will actually take time as a base then asynchronous code will be faster in some cases it will be around 100ms or in some it will 500ms as well.

Also read: RSA Algorithm an Asymmetric Key Encryption in Python

Leave a Reply

Your email address will not be published. Required fields are marked *