julia - 元素明智的操作数组 Julia

标签 julia elementwise-operations

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

去年关闭。




Improve this question




我是 julia 的新用户,我正在尝试了解在 julia 中编写快速代码的最佳实践是什么。我主要是在数组/矩阵中进行元素明智的操作。我尝试了一些代码来检查哪一个可以让我获得更高的速度

fbroadcast(a,b) = a .*= b;

function fcicle(a,b)
   @inbounds @simd for i in eachindex(a)
      a[i] *= b[i];
   end
end
a = rand(100,100);
b = rand(100,100);
@btime fbroadcast(a,b)
@btime fcicle(a,b)

使用 for 的功能实现了广播版本的 2 倍左右的速度。两种情况有什么区别?我希望广播在内部循环操作,这与我在 fcicle 上所做的非常相似。
最后,有没有什么方法可以通过像 a .*= b 这样的简短语法实现最佳速度?

非常感谢,
迪伦

最佳答案

我没想到会这样。这可能是性能错误吗?

同时,在这种情况下出现的广播性能问题似乎只出现在 2D 阵列中。以下看起来像一个丑陋的黑客,但它似乎恢复了性能:

function fbroadcast(a,b)
    a, b = reshape.((a, b), :) # convert a and b to 1D vectors
    a .*= b
end

function fcicle(a,b)
   @inbounds @simd for i in eachindex(a)
      a[i] *= b[i];
   end
end
julia> using BenchmarkTools
julia> a = rand(100, 100);
julia> b = rand(100, 100);

julia> @btime fbroadcast($a, $b);
  121.301 μs (4 allocations: 160 bytes)

julia> @btime fcicle($a, $b);
  122.012 μs (0 allocations: 0 bytes)

关于julia - 元素明智的操作数组 Julia ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403797/

相关文章:

arrays - Julia:eigs() 函数不返回所有特征值

matlab - 如何在matlab中有效地构造一个依赖于索引的矩阵

julia - 使用 Julia 的点符号和就地操作

matlab - matlab 中的 Elementwise ifs - 它们存在吗?

julia - 类型的函数属性中的默认参数

julia - 函数 Base.+ 必须显式导入才能扩展

metaprogramming - 在运行时将变量保存到文件

julia - 使用梯度进行优化错误: "no method matching"

python - 如何在 Numpy 中有效地将二维数组中的每个元素乘以一维数组?