Skip to content

Instantly share code, notes, and snippets.

@dgerosa
Created June 27, 2021 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgerosa/69ce1e5fb653e7400c73811dbaa8bb1c to your computer and use it in GitHub Desktop.
Save dgerosa/69ce1e5fb653e7400c73811dbaa8bb1c to your computer and use it in GitHub Desktop.
Simple parallel jobs in python
import numpy as np
import multiprocessing, pathos.multiprocessing
from tqdm import tqdm
import os
#print(os.getpid())
# I want to execute a function...
def fun(a,b):
#print(os.getpid())
time.sleep(1) # So that it takes a bit longer...
return a+b
# ...on many values.
N=10
a=np.linspace(0,1,N)
b=np.linspace(0,1,N)
# I can do it with a for loop...
aplusb=[]
for ax,bx in tqdm(zip(a,b)):
aplusb.append(fun(a,b))
print(aplusb)
# ...or equivalently using python's map
aplusb = list(tqdm(map(fun, a,b),total=N))
print(aplusb)
# The latter can be easily generalized to run in parallel
# How many CPUs do you want?
#CPUS = multiprocessing.cpu_count() # All CPUs available
CPUS= 4 # Set manually
# Now, this is much faster!
parmap = pathos.multiprocessing.ProcessingPool(CPUS).imap
aplusb = list(tqdm(parmap(fun, a,b),total=N))
print(aplusb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment