我有以下的 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]
我有以下的 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]
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>
你好,Kira。
我是Julia的新手,但也遇到了同样的问题。尝试这种方法,看看是否符合你的需求。
function f(x)
return x^2;
end
y=@parallel vcat for i= 1:100
f(i);
end;
println(y)
尊敬的RN: