Improving code performance using @inbounds
Often, especially in performance-critical code, we want to squeeze the maximum speed out of Julia. If you are working with arrays, the @inbounds
macro can be used to significantly reduce access time to the elements. The drawback is that you have to be sure that you are not trying to access an out-of-bounds location.
Getting ready
Inspect the inbounds.jl
file that contains the following contents:
using BenchmarkTools mode = ["normal", "@inbounds"] i = 0 for inbounds in ["", "@inbounds"] global i += 1 eval(Meta.parse("""function f$i(x::AbstractArray{<:Real}) y = 0 $inbounds for i in eachindex(x) y += x[i] > 0.5 end y end""")) end x = rand(10^7) for (idx, f) in enumerate([f1, f2]) println("\n", mode[idx]) @btime $f($x) end
Note
In the GitHub repository for this recipe, you...