首页 > 解决方案 > 元素明智的操作数组朱莉娅

问题描述

我是一个新的 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 这样的简短语法来实现最佳速度?

非常感谢,迪伦

标签: juliaelementwise-operations

解决方案


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

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

推荐阅读