Parallel Processing In Python3

When running ๐Ÿ Python programs, some tasks take a long โณ time to complete. For example, calling an external ๐ŸŒ API or reading large ๐Ÿ“‚ files. If we run these tasks one by one, it can be ๐ŸŒ slow. Instead, we can run them in parallel to save โฑ๏ธ time.

๐Ÿ Python provides the concurrent.futures module to run tasks in parallel. It has two main classes:

  • ThreadPoolExecutor: Uses ๐Ÿงต threads, good for I/O-bound tasks (e.g., API calls, file ๐Ÿ“ I/O).
  • ProcessPoolExecutor: Uses ๐Ÿ–ฅ๏ธ processes, better for CPU-bound tasks (e.g., ๐Ÿงฎ calculations, data ๐Ÿ“Š processing).

Here is a simple example using ThreadPoolExecutor to make multiple ๐ŸŒ API requests faster.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import concurrent.futures
import requests

def fetch_url(url):
    response = requests.get(url)
    return url, response.status_code

urls = [
    "https://jsonplaceholder.typicode.com/posts/1",
    "https://jsonplaceholder.typicode.com/posts/2",
    "https://jsonplaceholder.typicode.com/posts/3",
]

with concurrent.futures.ThreadPoolExecutor() as executor:
    results = executor.map(fetch_url, urls)

for url, status in results:
    print(f"URL: {url}, Status Code: {status}")
  • We define a function fetch_url to get data ๐Ÿ“ก from a URL.
  • We use ThreadPoolExecutor to run fetch_url for multiple URLs in parallel.
  • The executor.map method applies the function to all URLs and returns results.

Besides concurrent.futures, ๐Ÿ Python has other ways to run tasks in parallel:

  • multiprocessing module: Runs tasks in separate ๐Ÿ–ฅ๏ธ processes.
  • asyncio module: Handles asynchronous tasks efficiently โšก.
  • joblib library: Useful for parallel computing in ๐Ÿง  machine learning.

Each method has its own use case. concurrent.futures is a simple and effective choice for many parallel tasks.

Using concurrent.futures, we can speed up โฉ tasks that involve I/O operations like API calls. It is easy ๐Ÿค“ to use and improves performance significantly ๐Ÿš€. If you need parallel processing in ๐Ÿ Python, give it a try! ๐Ÿ’ก

Related Content