Last active
June 20, 2019 11:28
-
-
Save astrojuanlu/6470913 to your computer and use it in GitHub Desktop.
Comparison between multiprocessing Pool and ProcessPoolExecutor from concurrent.futures.
This file contains 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
def hard_work(n): | |
""" A naive factorization method. Take integer 'n', return list of | |
factors. | |
""" | |
# Do some CPU bond work here | |
if n < 2: | |
return [] | |
factors = [] | |
p = 2 | |
while True: | |
if n == 1: | |
return factors | |
r = n % p | |
if r == 0: | |
factors.append(p) | |
n = n // p | |
elif p * p >= n: | |
factors.append(n) | |
return factors | |
elif p > 2: | |
# Advance in steps of 2 over odd numbers | |
p += 2 | |
else: | |
# If p == 2, get to 3 | |
p += 1 | |
assert False, "unreachable" | |
if __name__ == '__main__': | |
from concurrent.futures import ProcessPoolExecutor, wait | |
from multiprocessing import cpu_count | |
try: | |
workers = cpu_count() | |
except NotImplementedError: | |
workers = 1 | |
pool = ProcessPoolExecutor(max_workers=workers) | |
result = pool.map(hard_work, range(100, 10000)) |
This file contains 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
def hard_work(n): | |
""" A naive factorization method. Take integer 'n', return list of | |
factors. | |
""" | |
# Do some CPU bond work here | |
if n < 2: | |
return [] | |
factors = [] | |
p = 2 | |
while True: | |
if n == 1: | |
return factors | |
r = n % p | |
if r == 0: | |
factors.append(p) | |
n = n // p | |
elif p * p >= n: | |
factors.append(n) | |
return factors | |
elif p > 2: | |
# Advance in steps of 2 over odd numbers | |
p += 2 | |
else: | |
# If p == 2, get to 3 | |
p += 1 | |
assert False, "unreachable" | |
if __name__ == '__main__': | |
from multiprocessing import Pool, cpu_count | |
try: | |
workers = cpu_count() | |
except NotImplementedError: | |
workers = 1 | |
pool = Pool(processes=workers) | |
result = pool.map(hard_work, range(100, 10000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment