Consider the following code
using BenchmarkTools
using Random
using QuadGK
f(p, xm, x) = -x^2 / ((p[1] - xm[1]*x)^2 + (p[2] - xm[2]*x)^2)
g(p, xm, x) = -x^2 / ((p[1] - xm[1])^2 + (p[2] - xm[2])^2)
integralf(p, xm) = quadgk(x -> f(p, xm, x), 0.0, 1.0)
integralg(p, xm) = quadgk(x -> g(p, xm, x), 0.0, 1.0)
function test(p, xm, integral)
s = 0.0
for i in 1:1000
rand!(p)
rand!(xm)
res, err = integral(p, xm)
s += res
end
return s
end
p = zeros(Float64, 2)
xm = zeros(Float64, 2)
test(p, xm, integralf)
test(p, xm, integralg)
When I run the benchmarks, integralf
is allocating, whereas integralg
( which only has x^2
in it) is not, which I do not understand.
@benchmark test($p, $xm, $integralf)
@benchmark test($p, $xm, $integralg)
Can someone help me understanding what is going on?
EDIT: I think it is related to the fact that there are 1/(a-x)
kind of terms in the integrand, as shown by allocation profiler. With the division replaced by multiplication in f(p, xm, x)
, it vanishes.