Hello,
The time taken to compile the code is less for the nested for loop though I thought the Julia way is more efficient. Can anyone clarify?
The time taken to compile the code is less for the nested for loop though I thought the Julia way is more efficient. Can anyone clarify?
In general, Julia only compiles code put into functions. I recommend reading the performance tips section of the manual.
If you put it in a function, you get results like below (note that the bottleneck here probably is allocating the arrays)
julia> function f()
m, n = 5, 5
A = fill(0, (m, n))
for j in 1:n
for i in 1:m
A[i, j] = i + j
end
end
A
end
f (generic function with 1 method)
julia> using BenchmarkTools
julia> f()
5×5 Matrix{Int64}:
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
6 7 8 9 10
julia> @benchmark f()
BenchmarkTools.Trial: 10000 samples with 968 evaluations.
Range (min … max): 74.483 ns … 822.128 ns ┊ GC (min … max): 0.00% … 81.69%
Time (median): 78.448 ns ┊ GC (median): 0.00%
Time (mean ± σ): 84.993 ns ± 51.897 ns ┊ GC (mean ± σ): 3.91% ± 5.94%