Hot loop updating array elements with product over other array

Since sin and cos are your main bottle neck you can use a library that is optimized for computing these.

One of those is Yeppp.jl and using my upgrade for new Julia versions (https://github.com/JuliaMath/Yeppp.jl/pull/38) I get

function bg_sim_mwe(nB=100,nSamples=100)
    e = 0.9
    p = 0.8
    nt = 100

    t = range(0,stop=5.0,length=nt)

    V(ph, c, s) = 1.0 - p + p*(c + 1im*e*s)
    phi = zeros(nt)

    Vtotal = zeros(ComplexF64,nt)
    _cos = zeros(nt)
    _sin = zeros(nt)

    for a = 1:nSamples
        om = randn(nB)  # this replaces an actual calculation
        for it = 1:nt
            phi .= om .* t[it]
            Yeppp.cos!(_cos, phi)
            Yeppp.sin!(_sin, phi)

            Vtotal[it] += prod(v -> V(v...), zip(phi, _cos, _sin))
        end
    end
end
julia> @btime bg_sim_mwe()
  10.253 ms (20104 allocations: 716.89 KiB)

compared to before

julia> @btime bg_sim_mwe()
  21.192 ms (102 allocations: 90.14 KiB)
1 Like