对于矩阵运算,为什么是"ikj"?比"ijk"更快? [英] For matrix operation, Why is "ikj" faster than "ijk"?

查看:308
本文介绍了对于矩阵运算,为什么是"ikj"?比"ijk"更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于矩阵运算...

public static int[][] ijkAlgorithm(int[][] A, int[][] B) {
    int n = A.length;
    int[][] C = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return C;
}

ikj算法

public static int[][] ikjAlgorithm(int[][] A, int[][] B) {
    int n = A.length;
    int[][] C = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int k = 0; k < n; k++) {
            for (int j = 0; j < n; j++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return C;
}

我知道 ikj ijk 快,但不知道为什么.有什么简单的解释吗?谢谢.

I know ikj is faster than ijk, but don't know why. Have any simple explanation? Thank you.

推荐答案

在第二个代码段中,编译器可以优化

In the second snippet, the compiler can optimise

    for (int k = 0; k < n; k++) {
        for (int j = 0; j < n; j++) {
            C[i][j] += A[i][k] * B[k][j];
        }
    }

转换为

    for (int k = 0; k < n; k++) {
        int temp = A[i][k];  
        for (int j = 0; j < n; j++) {
            C[i][j] += temp * B[k][j];
        }
    }

,但是在第一个代码段中无法进行此类优化.因此,第二个片段需要更少的对数组的查找.

but no such optimisation can be made in the first snippet. So the second snippet requires fewer lookups into the arrays.

这篇关于对于矩阵运算,为什么是"ikj"?比"ijk"更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆