使用Apple Accelerate Framework vForce库来提高性能

Using the Apple Accelerate Framework vForce library to improve performance

本文关键字:高性能 vForce Apple Accelerate Framework 使用      更新时间:2023-10-16

我已经成功地从Apple的Accelerate Framework中实现了BLAS库,以提高我的基本向量和矩阵运算的性能。

对此感到满意的是,我将注意力转向了vForce,以矢量化我的基本数学函数。在这里,我有点惊讶地发现,与天真的实现(使用自动编译器优化-O)相比,性能相当差。

作为一个简单的基准测试,我运行了以下测试:Matrix是基本的Matrix类型,使用双指针,AccelerateMatrix是Matrix的一个子类,它使用vForce:中的求幂函数

Matrix A(vec_size);
AccelerateMatrix B(vec_size);
for (int i=0; i<vec_size;i++ ) {
    A[i] = i;
    B[i] = i;
}
double elapsed_time;
clock_t start = clock();
for(int i=0;i<reps;i++){
    A.exp();
    A.log();
}
clock_t stop = clock();
elapsed_time = (double)(stop-start)/CLOCKS_PER_SEC/reps;
cerr << "Basic matrix exponentiation/log time = " << elapsed_time << endl;

start = clock();
for(int i=0;i<reps;i++){
    B.exp();
    B.log();
}
stop = clock();
elapsed_time = (double)(stop-start)/CLOCKS_PER_SEC/reps;
cerr << "Accelerate matrix exponentiation/log time = " << elapsed_time << endl;

指数化/对数成员函数实现如下:

void AccelerateMatrix::exp(){
   int size =(int)this->getSize();
   this->goToStart();
   vvexp(this->ptr, this->ptr, &size);}
void Matrix::exp(){
    double *ptr = data;
    while (!atEnd()) {
        *ptr = std::exp(*ptr);
        ptr++;
    }
}

data是指向双数组的第一个元素的指针。

以下是性能的输出:

矩阵元素数=1000000

基本矩阵幂/对数时间(秒)=0.0089806

加速矩阵求幂/对数时间(秒)=0.0149955

我正在从XCode以Release模式运行。我的处理器是2.3 GHz的英特尔酷睿i7。内存为8 GB 1600 MHz DDR3。

问题似乎与vForce如何操纵内存有关。从本质上讲,它不擅长一次性处理大型矩阵。对于vec_size = 1000;,vForce计算指数/对数的速度是编译器优化的原始版本的两倍。我将更大的示例vec_size = 1000000分解为一批,每批1000个,瞧,vForce实现的速度是原始实现的两倍。美好的