Optimizing I/O-bound tasks involves using asynchronous programming and efficient I/O operations. CPU-bound tasks can be optimized using multi-processing and efficient algorithms.
Example for I/O-bound:
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return 'data'
# Example for CPU-bound
from multiprocessing import Pool
def compute(x):
return x * x
with Pool(5) as p:
print(p.map(compute, range(10)))