【发布时间】:2015-09-09 20:04:31
【问题描述】:
我正在 Ipython 中准备一个小型演示文稿,我想展示在 Julia 中进行并行操作是多么容易。
基本上是蒙特卡洛派计算described here
问题是我不能让它在 IPython (Jupyter) Notebook 中并行工作,它只使用一个。
我开始 Julia 时是:julia -p 4
如果我在 REPL 中定义函数并在那里运行它就可以了。
@everywhere function compute_pi(N::Int)
"""
Compute pi with a Monte Carlo simulation of N darts thrown in [-1,1]^2
Returns estimate of pi
"""
n_landed_in_circle = 0
for i = 1:N
x = rand() * 2 - 1 # uniformly distributed number on x-axis
y = rand() * 2 - 1 # uniformly distributed number on y-axis
r2 = x*x + y*y # radius squared, in radial coordinates
if r2 < 1.0
n_landed_in_circle += 1
end
end
return n_landed_in_circle / N * 4.0
end
function parallel_pi_computation(N::Int; ncores::Int=4)
"""
Compute pi in parallel, over ncores cores, with a Monte Carlo simulation throwing N total darts
"""
# compute sum of pi's estimated among all cores in parallel
sum_of_pis = @parallel (+) for i=1:ncores
compute_pi(int(N/ncores))
end
return sum_of_pis / ncores # average value
end
julia> @time parallel_pi_computation(int(1e9))
elapsed time: 2.702617652 seconds (93400 bytes allocated)
3.1416044160000003
但是当我这样做时:
using IJulia
notebook()
并尝试在仅使用 1 个核心的笔记本中做同样的事情:
In [5]: @time parallel_pi_computation(int(10e8))
elapsed time: 10.277870808 seconds (219188 bytes allocated)
Out[5]: 3.141679988
那么,为什么 Jupyter 不使用所有内核?我该怎么做才能让它发挥作用?
谢谢。
【问题讨论】:
-
你有没有试过修改对应的
kernel.json文件并在那里添加-p开关? -
如果
addprocs(4)首先在笔记本中发出会怎样? -
@rickhg12hs,我认为这应该可行,如果是这样,这是一个比我丑陋的内核文件破解更好的解决方案。
-
@rickhg12hs 谢谢。效果很好。
-
我会将我的评论转换为答案,以便其他人更容易找到它。
标签: parallel-processing ipython-notebook julia jupyter