In [1]:
import numpy as np
import numba
import multiprocessing as mp
from concurrent.futures import ThreadPoolExecutor
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
In [2]:
def in_unit_circle(x, y):
if x**2 + y**2 < 1:
return 1
else:
return 0
In [3]:
@numba.vectorize('int64(float64, float64)',target='cpu')
def in_unit_circle_serial(x, y):
if x**2 + y**2 < 1:
return 1
else:
return 0
In [4]:
@numba.vectorize('int64(float64, float64)',target='parallel')
def in_unit_circle_multicore(x, y):
if x**2 + y**2 < 1:
return 1
else:
return 0
In [5]:
n = int(1e7)
xs, ys = np.random.random((2, n))
In [6]:
%%time
4 * np.sum(in_unit_circle(x, y) for x, y in zip(xs, ys))/n
Out[6]:
In [7]:
%%time
4 * np.sum(in_unit_circle_serial(xs, ys))/n
Out[7]:
In [8]:
%%time
4 * np.sum(in_unit_circle_multicore(xs, ys))/n
Out[8]:
In [9]:
def plot_one(data, name):
xs, ys = data.T
plt.scatter(xs, ys, s=1, edgecolor=None)
plt.savefig('%s.png' % name)
return name
In [10]:
data = np.random.random((10, 10000, 2))
In [11]:
%%time
for i, M in enumerate(data):
plot_one(M, i)
%%time
args = [(x, i) for i, x in enumerate(data)]
def plot_one_(arg):
return plot_one(*arg)
with ThreadPoolExecutor() as pool:
pool.map(plot_one_, args)
In [12]:
%%time
args = [(x, i) for i, x in enumerate(data)]
with mp.Pool() as pool:
pool.starmap(plot_one, args)
In [13]:
%%time
args = [(x, i) for i, x in enumerate(data)]
with mp.Pool() as pool:
results = pool.starmap_async(plot_one, args)
In [14]:
%%time
Parallel(n_jobs=-1)(delayed(plot_one)(x, i) for i, x in enumerate(data))
pass
In [15]:
def f(x):
import time
time.sleep(np.random.randint(0, 5))
return x
In [16]:
%%time
with mp.Pool(processes=4) as pool:
result = pool.map(f, range(10))
In [17]:
result
Out[17]:
In [18]:
%%time
pool = mp.Pool(processes=4)
result = pool.map_async(f, range(10))
In [20]:
if result.ready() and result.successful():
print(result.get())
else:
print(result.wait())