I found some time to profile my code with the intention of reducing memory use and number of allocations. A quick check revealed that the function check_inequalities
was the main culprit for the allocations: in my bigger piece of code, I first had a Memory estimate: 1.81 GiB, allocs estimate: 17908475.
, which then reduced to a Memory estimate: 1.36 GiB, allocs estimate: 2907475.
when I replaced the function by check_inequalities_efficient
. Still a lot to do of course, but this is a factor 6 reduction in allocations for a simple one-line change!
I was just wondering if that function is the idiomatic Julia way of doing things, or if there is a more efficient method/idiomatic way of getting an allocation free version of check_inequalities
?
using BenchmarkTools, Random
Random.seed!(42)
struct RectangleSpace{T<:Real, U<:Real}
lower_bounds::Vector{T}
upper_bounds::Vector{U}
end
check_inequalities(x::Vector{Float64}, rectangle::RectangleSpace) = all(rectangle.lower_bounds .<= x .<= rectangle.upper_bounds)
check_inequalities_efficient(x::Vector{Float64}, rectangle::RectangleSpace) = all(y -> rectangle.lower_bounds[y[1]] <= y[2] <= rectangle.upper_bounds[y[1]], enumerate(x))
function RunBench()
X = rand(5)
rectangle = RectangleSpace(fill(0.0, 5), fill(0.5, 5))
bench = @benchmark check_inequalities($X, $rectangle)
display(bench)
bench2 = @benchmark check_inequalities_efficient($X, $rectangle)
display(bench2)
end
RunBench()
gives
BenchmarkTools.Trial: 10000 samples with 991 evaluations.
Range (min β¦ max): 41.120 ns β¦ 2.808 ΞΌs β GC (min β¦ max): 0.00% β¦ 97.79%
Time (median): 41.835 ns β GC (median): 0.00%
Time (mean Β± Ο): 46.299 ns Β± 73.889 ns β GC (mean Β± Ο): 7.60% Β± 4.78%
βββββββββ βββββ β
ββββββββββββββββββββββββββββββββββ
βββββ
β
β
β
β
β
βββ
ββββ
βββ
βββββ
β
41.1 ns Histogram: log(frequency) by time 56.9 ns <
Memory estimate: 96 bytes, allocs estimate: 3.
BenchmarkTools.Trial: 10000 samples with 1000 evaluations.
Range (min β¦ max): 2.834 ns β¦ 23.917 ns β GC (min β¦ max): 0.00% β¦ 0.00%
Time (median): 2.958 ns β GC (median): 0.00%
Time (mean Β± Ο): 2.978 ns Β± 0.278 ns β GC (mean Β± Ο): 0.00% Β± 0.00%
β β βββ β β
βββββββββββββββββββ
βββββ
ββββββββββ
ββββββββββββ
ββββ
ββββββββ β
2.83 ns Histogram: log(frequency) by time 4.04 ns <
Memory estimate: 0 bytes, allocs estimate: 0.