2015-11-03 97 views
2

我有一些代碼使用@parallel for循環進行計算,在每次迭代時產生一個輸出元組。我想作進一步處理陣列收集這些元組:收集for循環的元組數組

n=2 
out = @sync @parallel (hcat) for i=1:n 
    (i, i+1) 
end 
for i=1:n 
    (j,k) = out[i] 
    # do something 
end 
println("okay") 

如果這裏只有一個循環的迭代,out是一個元組,而不是元組的數組,(j,k) = out[i]拋出一個錯誤。

n=1 
out = @sync @parallel (hcat) for i=1:n 
    (i, i+1) 
end 
for i=1:n 
    (j,k) = out[i] # error 
    # do something 
end 
println("not reached") 

有沒有一種方法,我可以強制out是元組的數組無論n的價值,而不必循環後做out任何檢查?

謝謝。

回答

6

當你調用Tuple...hcat,你會被引導到一個更一般的算法:

julia> @which hcat((1,2)) 
hcat{T}(X::T...) at abstractarray.jl:710 

julia> @which hcat([(1,2)]) 
hcat{T}(V::Array{T,1}...) at array.jl:690 

,它需要更多的時間朱莉婭做hcat

julia> @time out = @sync @parallel (hcat) for i=1:10_000 
      (i, i+1) 
     end; 
0.146527 seconds (4.67 k allocations: 508.905 KB) 

julia> @time out = @sync @parallel (hcat) for i=1:10_000 
      [(i, i+1)] 
     end; 
0.061976 seconds (4.76 k allocations: 513.370 KB) 

另外,如果你使用第二種語法,不要錯誤n=1

n=1 
out = @sync @parallel (hcat) for i=1:n 
    [(i, i+1)] 
end 
for i=1:n 
    (j,k) = out[i] # OK 
    # do something 
end 
2

由於hcat(hcat(x)) = hcat(x),但始終是矩陣。您可以添加:

out = hcat(out) 

之後的並行循環。但是,這似乎是一個黑客。

+0

@ Reza的回答:用'[(i,i + 1)]替換'(i,i + 1)''看起來更好。在任何情況下,平行循環超過1個元素都會導致一些開銷。 –