用C语言实现顺序矩阵乘法的最快方法
我需要编写一个在C中执行矩阵求幂的快速算法。我编写了一个递归版本和一个迭代版本的平方求幂。矩阵不保证有特征值。这是我的密码: (matrix_multiply函数具有良好的性能——它使用SIMD和openMP进行了优化,缓存未命中率相对较低。) 迭代版本用C语言实现顺序矩阵乘法的最快方法,c,caching,optimization,memory,matrix-multiplication,C,Caching,Optimization,Memory,Matrix Multiplication,我需要编写一个在C中执行矩阵求幂的快速算法。我编写了一个递归版本和一个迭代版本的平方求幂。矩阵不保证有特征值。这是我的密码: (matrix_multiply函数具有良好的性能——它使用SIMD和openMP进行了优化,缓存未命中率相对较低。) 迭代版本 int matrix_power(matrix *result, matrix *mat, int pow) { matrix *temp; matrix *temp2; allocate_mat
int matrix_power(matrix *result, matrix *mat, int pow) {
matrix *temp;
matrix *temp2;
allocate_matrix(&temp, mat->rows, mat->cols);
allocate_matrix(&temp2, mat->rows, mat->cols);
initialize_to_identity(result);
while (pow) {
if (pow & 1) {
copy_matrix(temp2, result)
matrix_multiply(result, temp2, temp); //result = temp2 x temp
}
copy_matrix(temp2, temp);
mul_matrix(temp, temp2, temp2);
pow >>= 1;
}
destroy(&temp, mat->rows, mat->cols);
destroy(&temp2, mat->rows, mat->cols);
return 0;
}
递归版本:
int matrix_power(matrix *result, matrix *mat, int pow) {
matrix *temp;
allocate_matrix(&temp, mat->rows, mat->cols);
if (pow == 0) {
initialize_to_identity(result);
return 0;
}
if (pow == 1) {
copy_matrix(result, mat);
return 0;
} else if (pow == 2) {
matrix_multiply(result, mat, mat); //result = mat x mat
return 0;
}
matrix_power(temp, mat, pow >> 1);
matrix_multiply(result, temp, temp);
if (pow & 1) {
copy_matrix(temp, result);
matrix_multiply(result, temp, mat);
}
destroy(&temp, mat->rows, mat->cols);
return 0;
}
给定1000 x 1000矩阵,递归版本比迭代版本快1.5倍。我认为原因可能是迭代版本比递归版本做更多的复制。我尝试分配2个全局临时数组,这样我的递归代码就不需要在每次调用中分配2个临时数组,但我几乎看不到性能上的任何提高。如何更改代码以获得更好的性能