Julia并行计算在IPython Jupyter中

Est*_*ban 8 parallel-processing julia ipython-notebook jupyter

我正在Ipython中准备一个小小的演示文稿,我想展示在Julia中进行并行操作是多么容易.

它基本上是这里描述的蒙特卡罗Pi计算

问题是我无法在IPython(Jupyter)笔记本中并行工作,它只使用一个.

我开始朱莉娅: 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
Run Code Online (Sandbox Code Playgroud)

 

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
Run Code Online (Sandbox Code Playgroud)

 

julia> @time parallel_pi_computation(int(1e9))
elapsed time: 2.702617652 seconds (93400 bytes allocated)
3.1416044160000003
Run Code Online (Sandbox Code Playgroud)

但当我这样做时:

 using IJulia
 notebook()
Run Code Online (Sandbox Code Playgroud)

并尝试在Notebook内部执行相同的操作,它只使用1个核心:

In [5]:  @time parallel_pi_computation(int(10e8))
elapsed time: 10.277870808 seconds (219188 bytes allocated)

Out[5]:  3.141679988
Run Code Online (Sandbox Code Playgroud)

那么,为什么Jupyter不使用所有核心?我能做些什么才能让它发挥作用?

谢谢.

ric*_*2hs 12

addprocs(4)在笔记本中使用作为第一个命令应该提供四个工作人员在笔记本中进行并行操作.