[go: up one dir, main page]

0% found this document useful (0 votes)
2 views3 pages

Python - Sync Vs Threading Vs Async

The document explains the differences between synchronous, threading, and asynchronous programming in Python, highlighting the inefficiencies of synchronous code when making multiple network requests. It demonstrates how threading can improve performance but suggests that asynchronous programming is the most efficient method for handling network requests, achieving significant time savings. The document also advises on when to use each approach and cautions about potential rate limits when using async methods.

Uploaded by

Sathish Smart
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Python - Sync Vs Threading Vs Async

The document explains the differences between synchronous, threading, and asynchronous programming in Python, highlighting the inefficiencies of synchronous code when making multiple network requests. It demonstrates how threading can improve performance but suggests that asynchronous programming is the most efficient method for handling network requests, achieving significant time savings. The document also advises on when to use each approach and cautions about potential rate limits when using async methods.

Uploaded by

Sathish Smart
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python: Sync vs Threading vs

Async
Your Python code runs line by line. Each line waits for the previous one to
finish. Waiting for external responses? Your program just sits there doing
nothing.

Here’s how to fix that.

The Problem: Synchronous Code


import requests
import time

start = time.time()

for i in range(1, 2500):


response = requests.get(f'http://localhost:8000/api/{i}')
print(response.json())

print(f"Time taken: {time.time() - start:.2f} seconds")


# Output: Time taken: 5.85 seconds

This hits an endpoint 2500 times. Each request waits for the previous one.
5.85 seconds for a local server. Imagine thousands of URLs across the
internet.

Solution 1: Threading
from concurrent.futures import ThreadPoolExecutor
import requests
import time

def fetch_url(i):
response = requests.get(f'http://localhost:8000/api/{i}')
return response.json()

start = time.time()

with ThreadPoolExecutor() as executor:


results = executor.map(fetch_url, range(1, 2500))
for result in results:
print(result)
print(f"Time taken: {time.time() - start:.2f} seconds")
# Output: Time taken: 3.84 seconds

Better, but not great. Threading works best when your code is constantly
doing CPU work. Network requests? There’s a better way.

Solution 2: Async (The Winner)


import asyncio
import aiohttp
import time

async def fetch_url(session, i):


async with session.get(f'http://localhost:8000/api/{i}') as
response:
return await response.json()

async def main():


async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, i) for i in range(1, 2500)]
results = await asyncio.gather(*tasks)
for result in results:
print(result)

start = time.time()
asyncio.run(main())
print(f"Time taken: {time.time() - start:.2f} seconds")
# Output: Time taken: 1.34 seconds

1.34 seconds. Same 2500 requests. Fire them all at once, wait for
responses together. No wasted time.

When to Use What


Synchronous: Simple scripts, single requests, debugging.

Threading: CPU-heavy parallel work, when you can’t use async libraries.

Async: Network requests, I/O operations, APIs. This is your go-to.

One Catch: Rate Limits


Async will hammer servers fast. If your API allows 300 calls/minute and you
need 200, async gets them done in seconds. Synchronous? Could take
minutes.
Multiple different servers? Async shines. Same server with strict limits? Add
delays or use threading.

The speed difference is real. Pick the right tool.

You might also like