Edison Gustavo Muenz Edison Gustavo Muenz - 4 years ago 111
C Question

MKL or BLAS routine to multiply vector by a scalar out-of-place

I work in simulation software and one of the many operations done on arrays is scaling a vector by a number.

I have code like this:

//Just some initialization code, don't bother about this part
int n = 10000;
std::vector<double> input(n, 42.0);
std::vector<double> output(input.size());

double alpha = 69.0;

//the actual calculation:
for (size_t i = 0; i < n; ++i) {
output[i] = input[i] * alpha;

I have the MKL library available, so if my calculations are done "in-place" the following can be written:

cblas_dscal(n, alpha, &input[0], 1);

However, this will change the
variable, which is not what I want.

I tried using the
but it is very slow for this operation.

Answer Source

The solution I came up with was calling cblas_dcopy() then cblas_dscal().

It is not the best of all worlds but it is still faster than the raw loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download