2
我閱讀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);
}
}
首先,要測量時間,應該使用[ System.nanoTime'](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime())代替'System.currentTimeMillis',因爲前者更準確。其次,請參閱此鏈接以更好地瞭解有關微基準測試的信息:http://stackoverflow.com/q/504103/1065197 –
我對您的大矩陣結果有點好奇; 400x400在我的機器上垂直使用,但優勢急劇下滑:4000x4000是一個非常不同的故事。 – ljgw
是的,如果我檢查4000x4000或更大的矩陣,那麼水平掃描更快。這非常有趣! – ohmygoddess