Julia - Why Loops Faster

I have a background in MATLAB, so I have a tendency to vectorize everything. However, in July, I tested these two functions:

function testVec(n)
    t = [0 0 0 0];
    for i = 1:n
        for j = 1:4
            t[j] = i;
        end
    end
end

function testVec2(n)
    t = [0 0 0 0];
    for i = 1:n
        t.= [i i i i];
    end
end

@time testVec(10^4)
0.000029 seconds (6 allocations: 288 bytes)
@time testVec2(10^4)
0.000844 seconds (47.96 k allocations: 1.648 MiB)

I have two questions:

  • Why are cycles faster?
  • If loops are really faster, are there smart smart vectorization methods that mimic loops? The syntax for loops is ugly and long.
+4
source share
2 answers

In the method, the testVec2code will allocate a temporary vector to store [i i i i]for each instance iin your loop. This distribution is not free. You can see evidence of this in the number of deductions printed in your sync results. You can try the following:

function testVec3(n)
    t = [0 0 0 0]
    for i=1:n
        t .= i
    end
 end
+4
source
  • . , , Matlab. . @sam , , , . , Matlab, , , (, C Fortran), , .

  • , , @sam. , , .

+3

Source: https://habr.com/ru/post/1686238/


All Articles