I need to do several summations of specific matrix column(s). I can’t figure out a way to get rid of temporary allocations.
The code below is my best version, but it leaves a lot to be desired. If I don’t use @view, time and allocations are worse.
specialArray
is the array I am after. Each element in it is the result of several summations.
I don’t think any array size patterns should be capitalized on since in the real code everything is varied. I say this because indexArray is always indexing sets of 3, but that is not always the case.
using LinearAlgebra: dot
using BenchmarkTools
################ Setup the problem #################
nCharge = 3000
nMol = 1000
array1 = ones(Float64, nMol,nMol) * 3
array2 = ones(Float64, nCharge,nCharge) * 0.5
array3 = ones(Float64, nCharge) * 0.25
specialArray = zeros(nMol)
indexArray = [0 for i=1:nMol, j=1:2]
iIndex = 1
jIndex = 3
for i=1:nMol
global iIndex, jIndex
indexArray[i,1] = iIndex
indexArray[i,2] = jIndex
iIndex += 3
jIndex += 3
end
################ Define the problem #################
function SumThingsUp!(specialArray::Vector, array1::SubArray, array2::SubArray,
array3::SubArray, indexArray::SubArray)
for i = 1:length(specialArray)
st, ed = indexArray[i,1], indexArray[i,2]
specialArray[i] = sum(sum,@view(array1[i,:])) +
sum(sum,@view(array2[:,st:ed])) +
dot(@view(array3[st:ed]) , @view(array3[st:ed]) )
end
return specialArray
end
################ Run the problem #################
@btime SumThingsUp!($specialArray, $@view(array1[:,:]), $@view(array2[:,:]), $@view(array3[:]), $@view(indexArray[:,:]))
Each element in specialArray
for this MWE should be 7500.1875
. The fact that all indices are the same is not a reflection of the real problem, but the nature of the MWE.
Currently @btime
produces 15.488 ms (4000 allocations: 203.13 KiB)
Should I just make a function with for loops
for doing the summations manually?