Skip to content

Instantly share code, notes, and snippets.

@astrojuanlu
Last active June 20, 2019 11:28
Show Gist options
  • Save astrojuanlu/6470913 to your computer and use it in GitHub Desktop.
Save astrojuanlu/6470913 to your computer and use it in GitHub Desktop.
Comparison between multiprocessing Pool and ProcessPoolExecutor from concurrent.futures.
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))
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