Why the execution time of “testS()” is faster than “testP()”, although the later has reduced a “for loop” (which is supposed to consume time) by a direct assignment of the Matrix, as shown below:
using BenchmarkTools
function testS(S,r)
for i in size(S,1)
if r==1
for j in size(S,2)
S[i,j] = S[i,j] +1;
end
elseif r==2
for j in size(S,2)
S[i,j] = S[i,j] +2;
end
end
end
end
function testP(S,r)
for i in size(S,1)
if r==1
S[i,:] = [S[i,1]+1 S[i,2]+1 S[i,3]+1 S[i,4]+1];
elseif r==2
S[i,:] = [S[i,1]+2 S[i,2]+2 S[i,3]+2 S[i,4]+2];
end
end
end
dt = 0.0001;
tmin = 0;
tmax = 1;
timeSim = tmin:dt:tmax;
S = [0 0 0 0; 0 0 0 0; 0 0 0 0]
r = 1;
@btime begin for t in tmin:dt:tmax testS(S,r) end end
# It gives 595.700 μs
@btime begin for t in tmin:dt:tmax testP(S,r) end end
# It gives 949.500 μs