import numpy as np
from ipyparallel import Client # IPython.parallel before IPython 4.0
rc = Client()
rc.ids
[0, 1, 2, 3]
%px import os, time
%px print(os.getpid())
[stdout:0] 11173 [stdout:1] 11174 [stdout:2] 11175 [stdout:3] 11176
%%px --targets :-1
print(os.getpid())
[stdout:0] 11173 [stdout:1] 11174 [stdout:2] 11175
view = rc[:-1]
view
<DirectView [0, 1, 2]>
v = rc.load_balanced_view()
def sample(n):
import numpy as np
# Random coordinates.
x, y = np.random.rand(2, n)
# Square distances to the origin.
r_square = x ** 2 + y ** 2
# Number of points in the quarter disc.
return (r_square <= 1).sum()
def pi(n_in, n):
return 4. * float(n_in) / n
n = 100000000
pi(sample(n), n)
3.14174968
%timeit pi(sample(n), n)
1 loops, best of 3: 2.65 s per loop
args = [n // 100] * 100
ar = v.map(sample, args)
ar.ready(), ar.progress
(False, 12)
ar.elapsed, ar.serial_time
(1.428284, 4.042367000000002)
pi(np.sum(ar.result()), n)
3.141666