如何解决C样式的矩阵乘法3个循环比本征更快,是否有意义?
我正在阅读一些C编程教科书以进行精读,而我个人更喜欢C ++而不是C(对于我的程序类型)的主要原因之一就是Eigen线性代数。 因此,今天我只是对10x10矩阵乘法进行了简单测试,并测量了时间,至少令我惊讶的是,C风格已被证明是速度更快。在发布模式下,我平均C的
是否确实如此?如果是(或否),为什么?我不会以任何方式抹黑Eigen,仍然是我的顶级线性代数库,它提供了许多其他功能。作为热情的Eigen用户,可以采取一些措施来提高情景设计中的性能,如下所示。
// function to multiply two matrices
void multiplyMatrices(int first[][10],int second[][10],int result[][10],int r1,int c1,int r2,int c2) {
// Multiplying first and second matrices and storing it in result
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
// Init matrix
result[i][j] = 0;
for (int k = 0; k < c1; ++k) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
}
int main() {
int first[10][10],second[10][10],result[10][10];
// Initializing elements to something arbitrary
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
first[i][j] = i * j;
second[i][j] = (i + 3) * j;
}
}
// multiply two matrices,only time the multiplication
auto t1 = std::chrono::high_resolution_clock::now();
multiplyMatrices(first,second,result,10,10);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << "C style: " << duration << std::endl;
// Initialize the matrices to a fixed size
Eigen::Matrix<int,10> f1(10,10);
Eigen::Matrix<int,10> f2(10,10> r(10,10);
// Same initialization values as C style
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
f1(i,j) = i * j;
f2(i,j) = (i + 3) * j;
}
}
// Only time the multiplication
t1 = std::chrono::high_resolution_clock::now();
r = f1 * f2;
t2 = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << "Eigen: " << duration << std::endl;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。