DEV Community

Cover image for How One Code Update ⚑ Supercharged My Python Performance πŸš€!
awedis for AWS Heroes

Posted on

How One Code Update ⚑ Supercharged My Python Performance πŸš€!

Hello Pythoners! 🐍

I was experimenting something lately with python code and was able to conduct small experiment that thought would be nice to share it here with you.

Let's say you are doing API calls from python and you are using for loop for example, but that loop will take some time to finish all the requests, and return the responses in a synchronous way. However you can use Async http calls using this library called Aiohttp.

Aiohttp library in Python is an asynchronous HTTP client and server framework that is built on top of the asynchronous I/O library asyncio in Python. Using this library, we can build web applications and RESTful APIs, and also we can handle synchronous HTTP requests in the application.

Here is a simple code example that I tried it, and the performance improvement is shown in the below picture (AWS EC2 Monitoring section).

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            tasks.append(fetch_url(url, session))
        await asyncio.gather(*tasks)
Enter fullscreen mode Exit fullscreen mode

Image description

In the above picture we can see how much the cpu and network utilization was optimized by this simple code improvement.

Another example: Let’s say you’re processing a large amount of images for resizing. Instead of resizing them one by one, you can use asynchronous programming to handle them concurrently.

VoilΓ ! πŸ₯Ή my code now runs much faster.

Image description

Conclusion, always remember code optimization is sooo.. important specially when we are living in an era where big amount of resources can be provided by just a click of button. That small peace of code that you are writing right now, one day might actually handle millions of traffic, and hence optimization is so important.

Thank you for reading my article, let's stay connected via the links below

πŸ‘‰ Follow me for more πŸ‘Ύ
LinkedIn
X

Top comments (0)