gpt4 book ai didi

arrays - Julia代码优化: vector calculation and taking sum

转载 作者:行者123 更新时间:2023-12-02 02:09:57 24 4
gpt4 key购买 nike

我在一个 Julia 项目中,我想优化下面代码中的函数 oneAttempt

下面是我的代码的简要说明:

  • 函数oneAttmept实现一定的递归算法,返回最终结果。
  • 变量f是通过我在下面的代码中编写为算法部分的算法更新的变量(对于这个问题我会省略这部分)。
  • 函数 oneAttempt 在 for 循环下会被调用很多次(超过 1000 次)。
function oneAttempt()
n = 30
m = 900

x = rand(Normal(), n, n)
A = ones(n, n) * sum(sum(x, dims = 1))

# f would be passed to the algorithm below.
# f0 is the initial value of f
f0 = ones(n, n) + x - (1 / m) * A
f = copy(f0)
o = zeros(n, n)

#=
algorithm part:
while loop in which f would be updated many times under complicated algorithm
=#

return f;
end

# the function `oneAttempt` would be called many times (more than 1000 times) under for loop.

我想有更好的优化方法来制作 f0,因为我听说向量计算将是 Julia 编码中的一个常见瓶颈。

有更好的编码方法吗?

如有任何信息,我们将不胜感激。

最佳答案

您的示例不太独立,这使得提出改进建议变得更加困难,因为我不知道可以在不改变其功能的情况下更改哪些部分。但总的来说,我想说你的问题是你创建了很多不必要的数组,你的第一个策略应该是减少它。

例如:

A = ones(n, n) * sum(sum(x, dims = 1))

这会在内部sum内部创建一个向量,然后对其求和。另外,不需要 ones(n, n) 它只是更多没有目的的分配。相反,写

A = sum(x)

这对整个数组x求和,不需要数组。 (我怀疑你来自 Matlab,其中 sum(x) 对矩阵的列求和(除非它是 1xN 矩阵,在这种情况下它对行求和!),但即使在 Matlab 中你也可以编写 sum(x, [], 'all') 而不是 sum(sum(x))。)

这里:

f0 = ones(n, n) + x - (1 / m) * A

您还应该避免不必要的分配。无需创建数组,只需使用广播即可。我会这样写:

f0 = (1 + A/m) .+ x  # 1 and A/m are both scalar, so don't dot the plus in the parens.

这里

f = copy(f0)
o = zeros(n, n)

您创建了更多数组,其中包含一个副本和。我不知道它们的用途,但我怀疑你不需要它。如果您添加更多上下文,我可以对其发表评论。

但总的来说,减少不必要的数组,改用广播,以及可能的就地操作。

关于arrays - Julia代码优化: vector calculation and taking sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67858075/

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