Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store result of sparse mat-vec-mult into pre-allocated vector

Tags:

c++

eigen

I'm working on a routine for sparse matrix-vector multiplication and want to create a reference performance benchmark using the Eigen3 library. I only want to benchmark the actual arithmetic without the memory allocation involved in the construction of the result vector. How can this be achieved?

I tried to assign the result to a pre-allocated vector but Eigen::internal::set_is_malloc_allowed reveals that some memory allocation is performed despite all my attempts.

// Setup multiplicands
const Eigen::SparseMatrix<double, Eigen::RowMajor> A = createMat();
const Eigen::VectorXd x = Eigen::VectorXd::Random(num_of_cols);
// Pre-allocate result vector
Eigen::VectorXd y = Eigen::VectorXd::Zero(num_of_rows);

Eigen::internal::set_is_malloc_allowed(false);
y = A * x; // <-- Runtime-error in debug mode
Eigen::internal::set_is_malloc_allowed(true);

What I'm looking for is basically a flavor of the sparse matrix-vector multiplication which takes a reference to an output buffer where the result is written to. Instead of y = A * x in the above example I would then write something like matVecMult(A, x, std::begin(y)). Is there a way to make this happen?

Kind regards.

like image 467
Slavistan Slavistan Avatar asked Jan 31 '26 18:01

Slavistan Slavistan


1 Answers

Try this:

y.noalias() = A * x;

noalias() indicates to Eigen that there is no potential aliasing issue involved (i.e., y does not overlap with x), and that Eigen shouldn't create a temporary.

like image 129
PlinyTheElder Avatar answered Feb 02 '26 06:02

PlinyTheElder