Last active
June 19, 2018 22:10
-
-
Save adamloving/81835cdfe01752abd21dbfde5de42eb4 to your computer and use it in GitHub Desktop.
parallelize python method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing, concurrent.futures | |
from functools import partial | |
WORKER_THREAD_COUNT = multiprocessing.cpu_count() | |
def parallelize(partials): | |
results = [] | |
with concurrent.futures.ProcessPoolExecutor(max_workers=WORKER_THREAD_COUNT) as executor: | |
jobs = [ executor.submit(p) for p in partials ] | |
for future in concurrent.futures.as_completed(jobs): | |
results.append(future.result()) | |
return results | |
# example | |
def work(x): print(x) | |
items = [1,2,3] | |
partials = map(lambda item: partial(work, item), items) | |
results = parallelize(partials) |
Refactored using partials (curried functions) so that parallelize doesn't need to care about function arguments.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍