BLAS中的元素向量 - 向量乘法?

Tar*_*rek 13 c++ blas

有没有办法用BLAS,GSL或任何其他高性能库进行元素矢量矢量乘法?

fin*_*nnw 10

(从字面上看问题的标题......)

是的,它可以单独用BLAS完成(虽然它可能不是最有效的方法.)

诀窍是将其中一个输入向量视为对角矩阵:

?a    ? ?x?    ?ax?
?  b  ? ?y? =  ?by?
?    c? ?z?    ?cz?
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用矩阵向量乘法函数之一,该函数可以将对角矩阵作为输入而无需填充,例如 SBMV

例:

void ebeMultiply(const int n, const double *a, const double *x, double *y)
{
    extern void dsbmv_(const char *uplo,
                       const int *n,
                       const int *k,
                       const double *alpha,
                       const double *a,
                       const int *lda,
                       const double *x,
                       const int *incx,
                       const double *beta,
                       double *y,
                       const int *incy);

    static const int k = 0; // Just the diagonal; 0 super-diagonal bands
    static const double alpha = 1.0;
    static const int lda = 1;
    static const int incx = 1;
    static const double beta = 0.0;
    static const int incy = 1;

    dsbmv_("L", &n, &k, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}

// Test
#define N 3
static const double a[N] = {1,3,5};
static const double b[N] = {1,10,100};
static double c[N];

int main(int argc, char **argv)
{
    ebeMultiply(N, a, b, c);
    printf("Result: [%f %f %f]\n", c[0], c[1], c[2]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Result: [1.000000 30.000000 500.000000]

  • 我知道这已经很晚了,但我只是想说虽然这个答案是由finnw有效的,但我不建议使用它.在我的实际案例中,只是自己编写循环要快得多(2-3次).我不知道我的编译器优化了多少,但通常切换到blas会产生一个很好的加速(例如在另一个方向上2-3次)而不是减速.当然,这取决于几个因素,但仅作为计算时间的警告. (2认同)

seh*_*ehe 7

总是存在std :: valarray 1 ,它定义了元素操作,/Quse-intel-optimized-headers如果目标支持它们,则经常(Intel C++ ,G ++)编译成SIMD指令.

这两个编译器也将进行自动矢量化

在那种情况下,你可以写

#define N 10000 

float a[N], b[N], c[N]; 

void f1() { 
  for (int i = 1; i < N; i++) 
  c[i] = a[i] + b[i]; 
} 
Run Code Online (Sandbox Code Playgroud)

并看到它编译成矢量化代码(例如使用SSE4)

1是的,它们过时且经常被认为是过时的,但在实践中它们都是标准的并且非常适合这项任务.


Tar*_*rek 6

我发现MKL在矢量数学函数库(VML)中有一整套数学运算,包括v?Mul,它可以满足我的需要.它适用于c ++数组,因此对我来说比GSL更方便.


jmb*_*mbr 5

在GSL,gsl_vector_mul诀窍.