-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharray-loops.jl
More file actions
39 lines (36 loc) · 1.2 KB
/
array-loops.jl
File metadata and controls
39 lines (36 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using BenchmarkTools
a = zeros(100,100)
function row_col_loop(a::AbstractArray)
nrows, ncols = size(a)
output = zeros(nrows, ncols)
for row in 1:nrows
for col in 1:ncols
output[row, col] = a[row, col]^2
end
end
end;
function col_row_loop(a::AbstractArray)
nrows, ncols = size(a)
output = zeros(nrows, ncols)
for col in 1:ncols
for row in 1:nrows
output[row, col] = a[row, col]^2
end
end
end;
function eachindex_loop(a::AbstractArray)
nrows, ncols = size(a)
output = zeros(nrows, ncols)
for id in eachindex(output)
output[id] = a[id]^2
end
end;
println()
println("-----------BENCHMARK-----------")
println()
println("Compute element-wise square of a 100x100 matrix in a new matrix")
print("row -> col:"); @btime row_col_loop(a);
print("col -> row:"); @btime col_row_loop(a);
print("eachindex: "); @btime eachindex_loop(a);
println("The eachindex loop is slower than the col -> row loop because of bounds checking (see the file array-loops-advanced.jl for more details)")
println("FYI, the eachindex loop achieves the performance of the row -> col loop when we mutate the input matrix instead of creating a new one...")