print('mult    ' + str(timeit.timeit('A += B * D', setup, number=3)))
print('index   ' + str(timeit.timeit('A[C] += D[C]', setup, number=3)))
setup3 = setup + """ 
A = np.ma.array(np.ones((dim, dim)), mask = np.array(B - 1, dtype = np.bool))
"""
print('ma      ' + str(timeit.timeit('A += D', setup3, number=3)))
setup4 = setup + """ 
from scipy import sparse
S = sparse.csr_matrix(C)
DS = S.multiply(D)
"""
print('sparse- ' + str(timeit.timeit('A += DS', setup4, number=3)))
setup5 = setup + """ 
from scipy import sparse
"""
print('sparse+ ' + str(timeit.timeit(
    'S = sparse.csr_matrix(C); DS = S.multiply(D); A += DS', setup4, number=3)))
setup6 = setup + """
from scipy import sparse
class Sparsemat(sparse.coo_matrix):
    def __iadd__(self, other):
        self.data += other.data
        return self
A = Sparsemat(sparse.rand(dim, dim, 0.5, 'coo')) 
D = np.random.random((dim, dim)) 
anz = A.nonzero()
"""
stmt6 = """
DS = Sparsemat((D[anz[0],anz[1]], anz), shape=A.shape) 
A += DS
"""
print('sparse2 ' + str(timeit.timeit(stmt6, setup6, number=3)))
Numpy arrays with mixed mutable and immutable values