问题
Why is adding a sparse and a full matrix slower than adding two full matrices? The following code demonstrates consistent superior performance for hFullAddFull
.
I_FULL = 600;
J_FULL = 10000;
FULL_COUNT = I_FULL*J_FULL;
NON_ZERO_ELEMENT_COUNT = 1000;
nonZeroIdxs = randsample(FULL_COUNT, NON_ZERO_ELEMENT_COUNT);
mat_Sp = spalloc(I_FULL, J_FULL, NON_ZERO_ELEMENT_COUNT);
mat_Sp(nonZeroIdxs) = 0.5;
mat_Full = full(mat_Sp);
otherMat_Full = rand(I_FULL, J_FULL);
hFullAddSp = @()otherMat_Full+mat_Sp;
hFullAddFull = @()otherMat_Full+mat_Full;
timeit(hFullAddSp)
timeit(hFullAddFull)
For me this is important as the addition occurs within a critical piece of code that is called 10,000s of times, so the small performance decrease for the sparse addition is critical. I would rather keep my code with the sparse type as input to the calculation and having the final matrix as a full matrix. Surely the 1000 elements of the full matrix can simply be modified? What is going on underneath here? Is there a way to make the sparse/full addition faster? Would a mex implementation be faster?
On my machine hFullAddFull
is 30% faster.
来源:https://stackoverflow.com/questions/49931838/matlab-why-is-full-sparse-matrix-addition-slower-than-full-full-matrix-addition