Reputation: 1172
I'm new to Julia and I was testing my understanding by the following benchmarks of three equivalent ways to set all elements of an Array smaller than 0.5
to 0.
:
using BenchmarkTools
function test!(A)
@btime begin # method 1
mask = $A .< 0.5
$A[mask] .= 0.
end
@btime begin # method 2
$A[$A .< 0.5] .= 0.
end
@btime begin # method 3
@inbounds begin
for i in eachindex($A)
if $A[i] < 0.5
$A[i] = 0.
end
end
end
end
end
n = 1000
test!(rand(n,n))
This outputs
1.612 ms (13 allocations: 3.94 MiB)
1.619 ms (13 allocations: 3.94 MiB)
4.215 ms (0 allocations: 0 bytes)
Based on what I have read about Julia until now I have several questions:
.
operator.Thank you for your time.
Upvotes: 3
Views: 116
Reputation: 6398
Your benchmark is kind of weird. If you instead define 3 functions like so,
function f1(A)
mask = A .< .5
A[mask] .= 0
end
function f2(A)
A[A .< .5] .= 0.
end
function f3(A)
@inbounds for i in eachindex(A)
if A[i] < .5
A[i] = 0.
end
end
end
and @btime
them, I get that f3
is about 2x faster.
Upvotes: 4