/*求一个二维数组每一列的和,用以测试计算机使用cache line方法后采用不同编写方式所带来的程序运行时间的差异*/
#include<iostream>
#include <time.h>
using namespace std;
int main() {
//初始化
int I = 10000, J = 10000, i = 0, j = 0;
int **d = new int*[I];
int * clomun = new int[I];
for (i = 0; i < I; i++) {
d[i] = new int[I];
for (j = 0; j < J; j++) {
d[i][j] = 1;
}
}
//按列取值
int start = clock(), end = 0;
for (j = 0; j <J; j++) {
clomun[j] = 0;
for (i = 0; i < I; i++)
clomun[j] += d[i][j];
}
end = clock();
cout << "按照列取值耗时为:" << end - start << endl;
//按行取值
start = clock(), end = 0;
for (i = 0; i < I; i++)
clomun[i] = 0;
for (i = 0; i < I; i++) {
for (j = 0; j <J; j++)
clomun[j]+= d[i][j];
}
end = clock();
cout << "按照行取值耗时为:" << end - start << endl;
return 0;
}
时间: 2024-10-23 07:47:54