Skip to content

Instantly share code, notes, and snippets.

@Mahyar24
Created March 10, 2023 20:30
Show Gist options
  • Save Mahyar24/49d59a855605a2aefe3a2618f7b2ba07 to your computer and use it in GitHub Desktop.
Save Mahyar24/49d59a855605a2aefe3a2618f7b2ba07 to your computer and use it in GitHub Desktop.
Make things parallel.
import math
from concurrent.futures import ProcessPoolExecutor, as_completed
from typing import Callable
def cut_list(data: list, n: int):
for i in range(1, math.ceil(len(data) / n) + 1):
yield data[(i - 1) * n: i * n]
def parallelize(func: Callable, inputs: list, n: int):
results = []
while len(inputs) != 1:
with ProcessPoolExecutor() as executor:
processes = [executor.submit(func, chunk) for chunk in cut_list(inputs, n)]
for process in as_completed(processes):
results.append(process.result())
inputs = results.copy()
results = []
return func(inputs)
if __name__ == "__main__":
parallelize(sum, list(range(1_000_000)), 100_000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment