水平或垂直循环通过2d阵列的效率

时间:2013-11-22 21:47:47

标签: java multidimensional-array

我在4年前发布的stackoverflow中读到了一篇文章,请看这里: Fastest way to loop through a 2d array? 几乎每个答案都认为水平扫描会更快。我写了一个简短的Java程序来检查这个,结果并非如此。我选择400x400矩阵。水平扫描的时间是6,垂直扫描的时间是3.我检查了其他尺寸的矩阵。它也证明垂直扫描更快。我是否会遗漏某些事情或确实如此?

public class Test {

public static void main(String[] args) {

        int row=Integer.parseInt(args[0]);
    int column=Integer.parseInt(args[1]);
    int[][] bigarray=new int[row][column];

    long startTime = System.currentTimeMillis();
    for(int i=0;i<row;i++)
        for(int j=0;j<column;j++)
            bigarray[i][j]=Math.abs(i-j)-Math.abs(i-j);


    long endTime   = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("scan horizentally time is: ");
    System.out.println(totalTime);

    int[][] bigarray1=new int[row][column];

    long startTime1 = System.currentTimeMillis();
    for(int j=0;j<column;j++)
        for(int i=0;i<row;i++)
            bigarray1[i][j]=Math.abs(i-j)-Math.abs(i-j);


    long endTime1   = System.currentTimeMillis();
    long totalTime1 = endTime1 - startTime1;
    System.out.println("scan vertically time is: ");
    System.out.println(totalTime1);

}

}

1 个答案:

答案 0 :(得分:0)

对于横向版本,您可以优化代码:

for(int i=0;i<row;i++)
    int[] rowArray = bigarray[i];
    for(int j=0;j<column;j++)
        rowArray[j]=Math.abs(i-j)-Math.abs(i-j);

如果您的测试设置第一次测试总是更慢,我不会感到惊讶。 Java需要大量的预热时间...更好的测试设置可能是拥有两个独立的程序,并在花时间之前采取一些预热循环......

相关问题