I have a function that checks if every element in an array is greater than a lower bound and lesser than an upper bound.
In the following code, I'm curious to know why bounds_error (a nested for-loop) is faster than bounds_error2 (vectorized, broadcast operation) and what can one do to make this function run faster.
using BenchmarkTools
function bounds_error(x, xl)
num_x_rows = size(x,1)
num_dim = size(xl, 1)
for i in 1:num_x_rows
for j in 1:num_dim
if (x[i, j] < xl[j,1] || x[i,j] > xl[j,2])
return true
end
end
end
return false
end
function bounds_error2(x, xl)
for row in eachrow(x)
xlt = transpose(xl)
if any(row .< xlt[1, :]) == true || any(row .> xlt[2, :])
return true
end
end
return false
end
#number of rows in xl (or xlimits) will always be equal to number of columns in x
xl = [ -5.0 5.0
-5.0 5.0
-5.0 5.0]
x = [1.0 2.0 3.0;
4.0 5.0 6.0]
@btime bounds_error(x, xl) #~20.645 ns (0 allocations: 0 bytes); true
@btime bounds_error2(x, xl) #~347.870 ns (12 allocations: 704 bytes); true