Element wise operations array julia

Viewed 816

I am a new julia user and I am trying to get a feeling on what is the best pratice to make fast code in julia. I am mainly making element wise operations in arrays/matrices. I tried a few codes to check which one allow me to get the higher speed

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)

Using the function with the for achieved a speed about 2x of the broadcast version. What are the differences between both cases? I would expect the broadcasting to internally loop the operations very similarly to what I did on the fcicle. Finally, is there any way of achieve the best speed with a short syntax like a .*= b?

Many thanks, Dylan

1 Answers

I wouldn't have expected this. Could it be a performance bug?

In the meantime, broadcast performance issues exhibited in this case only seem to appear for 2D arrays. The following looks like an ugly hack, but it seems to restore performance:

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)
Related