元素明智的操作数组朱莉娅

时间:2020-02-25 21:59:14

标签: julia elementwise-operations

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

anyOf

使用带有for的功能可以达到广播版本2倍的速度。两种情况有什么区别?我希望广播能够像在小插曲上那样在内部循环操作。 最后,有什么方法可以通过。* = b之类的短语法来达到最佳速度?

非常感谢, 迪伦

1 个答案:

答案 0 :(得分:3)

我不会想到这一点。可能是性能错误吗?

同时,在这种情况下出现的广播性能问题似乎只出现在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)