8

I'm preparing a small presentation in Ipython where I want to show how easy it is to do parallel operation in Julia.

It's basically a Monte Carlo Pi calculation described here

The problem is that I can't make it work in parallel inside an IPython (Jupyter) Notebook, it only uses one.

I started Julia as: julia -p 4

If I define the functions inside the REPL and run it there it works ok.

@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

But when I do:

 using IJulia
 notebook()

And try to do the same thing inside the Notebook it only uses 1 core:

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

Out[5]:  3.141679988

So, why isnt Jupyter using all the cores? What can I do to make it work?

Thanks.

4

3 回答 3

12

用作addprocs(4)笔记本中的第一个命令应该提供四个工作人员在笔记本中执行并行操作。

于 2015-06-25T12:10:10.470 回答
3

解决这个问题的一种方法是创建一个始终使用 4 个内核的内核。为此,需要一些手动工作。我假设你在一台 unix 机器上。

在文件夹~/.ipython/kernels/julia-0.x中,您将找到以下kernel.json文件:

{
  "display_name": "Julia 0.3.9",
  "argv": [
    "/usr/local/Cellar/julia/0.3.9_1/bin/julia",
    "-i",
    "-F",
    "/Users/ch/.julia/v0.3/IJulia/src/kernel.jl",
    "{connection_file}"
  ],
  "language": "julia"
}

如果复制整个文件夹cp -r julia-0.x julia-0.x-p4,并修改新复制的kernel.json文件:

{
  "display_name": "Julia 0.3.9 p4",
  "argv": [
    "/usr/local/Cellar/julia/0.3.9_1/bin/julia",
    "-p",
    "4",
    "-i",
    "-F",
    "/Users/ch/.julia/v0.3/IJulia/src/kernel.jl",
    "{connection_file}"
  ],
  "language": "julia"
}

路径对您来说可能会有所不同。请注意,我只给了内核一个新名称并添加了命令行参数`-p 4。

您应该会看到一个名为的新内核Julia 0.3.9 p4,它应该始终使用 4 个内核。

另请注意,此内核文件在您更新时不会得到更新IJulia,因此您必须在每次更新时手动更新它juliaIJulia.

于 2015-06-23T20:52:28.583 回答
0

您可以使用以下命令添加新内核:

using IJulia
#for 4 cores
installkernel("Julia_4_threads", env=Dict("JULIA_NUM_THREADS"=>"4"))

#or for 8 cores
installkernel("Julia_8_threads", env=Dict("JULIA_NUM_THREADS"=>"8"))

重新启动 VSCode 后,此选项将显示您的select kernel选项。

于 2021-12-17T14:07:37.203 回答