【问题标题】:Julia: Building multiple types in parallelJulia:并行构建多种类型
【发布时间】:2014-10-02 20:46:50
【问题描述】:

我正在尝试在 Julia 中使用并行性来构建几种大型类型(特别是通过 sklearn 到 PyCall 的高斯混合模型)。

如果我连续这样做,我会这样做:

models = Array(GMM, N)
for i = 1 : N
    params = ...
    models[i] = train_gmm(params)
end

但是,我应该能够做到这一点是并行的。我不知道从哪里开始,因为 SharedArrays 和 @parallel 对我来说似乎不是正确的选择。

我尝试使用@spawn,但发现以下内容:

function f1()
    rand(10000000)
    rand(10000000)
    rand(10000000)
    rand(10000000)
    rand(10000000)
end

function f2()
    a = @spawn rand(10000000)
    b = @spawn rand(10000000)
    c = @spawn rand(10000000)
    d = @spawn rand(10000000)
    e = @spawn rand(10000000)
    a_r = fetch(a)
    b_r = fetch(b)
    c_r = fetch(c)
    d_r = fetch(d)
    e_r = fetch(e)
end

f1()
f2()
println(@elapsed(f1()))
println(@elapsed(f2()))

f1 需要 0.21 秒,f2 需要 0.32 秒! @spawn 有什么我想念的吗?

编辑

看起来像在做:

function f1()
    [sum(rand(100000000)),
    sum(rand(100000000)),
    sum(rand(100000000)),
    sum(rand(100000000)),
    sum(rand(100000000))]
end

function f2()
    a = @spawn sum(rand(100000000))
    b = @spawn sum(rand(100000000))
    c = @spawn sum(rand(100000000))
    d = @spawn sum(rand(100000000))
    e = @spawn sum(rand(100000000))
    [fetch(a), fetch(b), fetch(c), fetch(d), fetch(e)]
end

导致 f2() 比 f1() 运行得更快,并且更符合我的要求。除非有人有更好的官方方式,否则我会这样做。

谢谢。

【问题讨论】:

    标签: julia


    【解决方案1】:

    我认为你的编辑是正确的。

    IAINMAC:~ idunning$ julia -p 3
    
    julia> @everywhere function foo()
             sleep(2)
           end
    
    julia> @time [foo(), foo(), foo()]
    elapsed time: 6.017959282 seconds (294088 bytes allocated)
    3-element Array{Nothing,1}:
     nothing
     nothing
     nothing
    
    julia> function bar()
             a = @spawn foo()
             b = @spawn foo()
             c = @spawn foo()
             [fetch(a), fetch(b), fetch(c)]
           end
    bar (generic function with 1 method)
    
    julia> @time bar()
    elapsed time: 2.030760103 seconds (199720 bytes allocated)
    3-element Array{Nothing,1}:
     nothing
     nothing
     nothing
    

    或者更优雅地使用pmap

    julia> @everywhere function foo(a::Int)
             sleep(a)
           end
    
    julia> @time pmap(foo,1:3)
    elapsed time: 3.004821524 seconds (448540 bytes allocated)
    3-element Array{Any,1}:
     nothing
     nothing
     nothing
    
    julia> @time map(foo,1:3)
    elapsed time: 6.006557822 seconds (1368 bytes allocated)
    3-element Array{Nothing,1}:
     nothing
     nothing
     nothing
    

    【讨论】:

    • 谢谢!将fetch 调用放在一个数组中是否会强制它们全部同时执行?
    • fetch 正在阻塞,所以我想他们按顺序阻塞,但我不确定(我猜这没关系)。这就是为什么使用 pmap 更好,因为它会触发前 N 个任务,并且一旦有任何返回,它就会启动一个新任务。
    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多