我有以下Julia代码,我想将其并行化。
using DistributedArrays
function f(x)
return x^2;
end
y = DArray[]
@parallel for i in 1:100
y[i] = f(i)
end
println(y)
输出为DistributedArrays.DArray[]
。我希望y的值如下:y=[1,4,9,16,...,10000]
答案 0 :(得分:13)
您可以使用n维分布式数组理解:
首先,您需要添加一些本地或远程进程:
julia> addprocs(CPU_CORES - 1);
然后你必须在每个衍生进程中使用 DistributedArrays
:
julia> @everywhere using DistributedArrays
最后,您可以使用@DArray
宏,如下所示:
julia> x = @DArray [@show x^2 for x = 1:10];
From worker 2: x ^ 2 = 1
From worker 2: x ^ 2 = 4
From worker 4: x ^ 2 = 64
From worker 2: x ^ 2 = 9
From worker 4: x ^ 2 = 81
From worker 4: x ^ 2 = 100
From worker 3: x ^ 2 = 16
From worker 3: x ^ 2 = 25
From worker 3: x ^ 2 = 36
From worker 3: x ^ 2 = 49
你可以看到它符合你的期望:
julia> x
10-element DistributedArrays.DArray{Int64,1,Array{Int64,1}}:
1
4
9
16
25
36
49
64
81
100
请记住,它适用于任意数量的维度:
julia> y = @DArray [@show i + j for i = 1:3, j = 4:6];
From worker 4: i + j = 7
From worker 4: i + j = 8
From worker 4: i + j = 9
From worker 2: i + j = 5
From worker 2: i + j = 6
From worker 2: i + j = 7
From worker 3: i + j = 6
From worker 3: i + j = 7
From worker 3: i + j = 8
julia> y
3x3 DistributedArrays.DArray{Int64,2,Array{Int64,2}}:
5 6 7
6 7 8
7 8 9
julia>
这是 julian 最符合您的意图恕我直言的方法。
我们可以查看macroexpand
输出,了解正在发生的事情:
注意:为了便于阅读,此输出已经过轻微编辑,T
代表:
DistributedArrays.Tuple{DistributedArrays.Vararg{DistributedArrays.UnitRange{DistributedArrays.Int}}}
julia> macroexpand(:(@DArray [i^2 for i = 1:10]))
:(
DistributedArrays.DArray(
(
#231#I::T -> begin
[i ^ 2 for i = (1:10)[#231#I[1]]]
end
),
DistributedArrays.tuple(DistributedArrays.length(1:10))
)
)
这与手动输入基本相同:
julia> n = 10; dims = (n,);
julia> DArray(x -> [i^2 for i = (1:n)[x[1]]], dims)
10-element DistributedArrays.DArray{Any,1,Array{Any,1}}:
1
4
9
16
25
36
49
64
81
100
julia>
答案 1 :(得分:3)
嗨基拉,
我是朱莉娅的新人,但面临同样的问题。尝试这种方法,看看它是否符合您的需求。
function f(x)
return x^2;
end
y=@parallel vcat for i= 1:100
f(i);
end;
println(y)
问候,RN