Kir*_*ira 15 parallel-processing julia
我有以下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)
Run Code Online (Sandbox Code Playgroud)
输出是DistributedArrays.DArray[].我希望y的值如下:y=[1,4,9,16,...,10000]
Sal*_*apa 14
您可以使用n维分布式数组解析:
首先,您需要添加更多进程,本地或远程:
julia> addprocs(CPU_CORES - 1);
Run Code Online (Sandbox Code Playgroud)
然后,你必须使用 DistributedArrays在衍生过程的每一个:
julia> @everywhere using DistributedArrays
Run Code Online (Sandbox Code Playgroud)
最后你可以使用@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
Run Code Online (Sandbox Code Playgroud)
你可以看到它符合你的期望:
julia> x
10-element DistributedArrays.DArray{Int64,1,Array{Int64,1}}:
1
4
9
16
25
36
49
64
81
100
Run Code Online (Sandbox Code Playgroud)
请记住,它适用于任意数量的维度:
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>
Run Code Online (Sandbox Code Playgroud)
这是最愚蠢的方式做你想要的恕我直言.
我们可以查看macroexpand输出以查看发生了什么:
注意:为了便于阅读,此输出已经过轻微编辑,T代表:
DistributedArrays.Tuple{DistributedArrays.Vararg{DistributedArrays.UnitRange{DistributedArrays.Int}}}
Run Code Online (Sandbox Code Playgroud)
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))
)
)
Run Code Online (Sandbox Code Playgroud)
这与手动输入基本相同:
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>
Run Code Online (Sandbox Code Playgroud)
嗨基拉,
我是 Julia 的新手,但面临着同样的问题。尝试这种方法,看看它是否适合您的需求。
function f(x)
return x^2;
end
y=@parallel vcat for i= 1:100
f(i);
end;
println(y)
Run Code Online (Sandbox Code Playgroud)
问候,注册护士