gpt4 book ai didi

parallel-processing - 如何在 julia 中编写并行循环?

转载 作者:行者123 更新时间:2023-12-03 20:29:53 24 4
gpt4 key购买 nike

我有以下 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]

最佳答案

您可以使用 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>

恕我直言,这是做你打算做的最朱利安的方式。

我们可以看看 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>

关于parallel-processing - 如何在 julia 中编写并行循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com