Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element wise operations array julia [closed]

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

like image 554
Dylan Avatar asked Feb 25 '20 21:02

Dylan


People also ask

How do you access an element in an array Julia?

In Julia, to access the contents/particular element of an array, you need to write the name of the array with the element number in square bracket. Now let us access the elements of 2-D.

Are arrays mutable in Julia?

Arrays in Julia are mutable and hence it allows modification of its content. Elements in arrays can be removed or updated as per requirement.

How do you fill an array in Julia?

Create an array filled with the value x . For example, fill(1.0, (10,10)) returns a 10x10 array of floats, with each element initialized to 1.0 . If x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating Foo() once.

How do you write a vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])


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)
like image 135
François Févotte Avatar answered Oct 17 '22 13:10

François Févotte