Junior — Middle
What methods exist for improving the efficiency of executing synchronous requests?
sobes.tech AI
Answer from AI
To improve the efficiency of executing synchronous requests in Python, the following approaches can be used:
- Parallelization using threads (threading) — allows running multiple requests simultaneously, especially if they are I/O-bound.
- Using multiprocessing — for CPU-bound tasks, to utilize multiple cores.
- Batch processing of requests — combining multiple requests into one, if supported by the server.
- Caching results — to avoid repeating requests for the same data.
An example using threading for parallel requests:
import threading
import requests
def fetch(url):
response = requests.get(url)
print(f"{url}: {response.status_code}")
urls = ["https://example.com", "https://python.org", "https://github.com"]
threads = []
for url in urls:
thread = threading.Thread(target=fetch, args=(url,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
This will speed up execution compared to sequential calls.