I’m thinking about optimizing performance and my mind initially goes to reducing the number of allocations. Below is a function with a loop that executes ~ 1,000,000 times.
When I “time” the routine, I find that it executes ~9 million reallocations. I just have no idea whether this is a lot and I should try to reduce it or whether this is about right.
function RK2(pend::pendulum;poincare::Bool= false)
r = [pend.thetaInitial,pend.omegaInitial]
t = 0.0
N = round(Integer,pend.tMax/pend.dt)
M = round(Integer,pend.omegaD * pend.tMax/(2π))
theta = zeros(Float64,N+1,1)
omega = zeros(Float64,N+1,1)
saveTheta = zeros(Float64,M,1)
saveOmega = zeros(Float64,M,1)
omega = zeros(Float64,N+1,1)
time = zeros(Float64,N+1,1)
theta[1] = pend.thetaInitial
omega[1] = pend.omegaInitial
time[1] = 0.0
counter = 2
index = 1
for i=1:N
k1 = pend.dt .* getDerivs(pend,r,t)
# test = getDerivs(pend,r,t + 1/2 * pend.dt)
k2 = pend.dt .* getDerivs(pend,r .+ 0.5 .* k1,t + 1/2 * pend.dt)
r += k2
if r[1] > π && pend.resets
r[1] -= 2π
elseif r[1] < -π && pend.resets
r[1] += 2π
end
if inPhase(pend,t)
saveTheta[index] = r[1]
saveOmega[index] = r[2]
index += 1
end
t+= pend.dt
theta[counter] = r[1]
omega[counter] = r[2]
time[counter] = t
counter += 1
end
if poincare
saveTheta,saveOmega
else
time,theta,omega
end
end