我想计算这两种方式的访问时间:Row major和Column major 因为我们知道C / C ++是Row major,所以当我们以第一种方式处理(Row major)时,我们应该更快。 但是用C ++语言看这段代码
#include <iostream>
#include <time.h>
#include <cstdio>
clock_t RowMajor()
{
char* buf =new char [20000,20000];
clock_t start = clock();
for (int i = 0; i < 20000; i++)
for (int j = 0; j <20000; j++)
{
++buf[i,j];
}
clock_t elapsed = clock() - start;
delete [] buf;
return elapsed ;
}
clock_t ColumnMajor()
{
char* buf =new char[20000,20000];
clock_t start = clock();
for (int i = 0; i < 20000; i++)
for (int j = 0; j < 20000; j++)
{
++buf[j,i];
}
clock_t elapsed = clock() - start;
delete [] buf;
return elapsed ;
}
int main()
{
std::cout << "Process Started." << std::endl;
printf( "ColumnMajor took %lu microSeconds. \n", ColumnMajor()*1000000/ (CLOCKS_PER_SEC) );
printf( "RowMajor took %lu microSeconds. \n", RowMajor() *1000000/ (CLOCKS_PER_SEC) );
std::cout << "done" << std::endl; return 0;
}
但每当我运行此代码时,我会得到不同的答案,有时Rowmajor时间比列主要时间更重,有时相反, 任何帮助都是有帮助的。
答案 0 :(得分:3)
在c ++中,coma operator不能用于创建/访问矩阵的东西。要创建matrix
,您需要跟踪with
和height
并将所有内存分配为数组。基本上你需要创建一个数字或元素等价于矩阵中元素数量的向量,你可以通过x + y * width
得到每个元素。
clock_t RowMajor()
{
int width = 20000;
int height = 20000;
char* buf = new char[width * height];
clock_t start = clock();
for (int j = 0; j < height; j++)
for (int i = 0; i < width; i++)
{
++buf[i + width * j];
}
clock_t elapsed = clock() - start;
delete[] buf;
return elapsed;
}
ColumnMajor
需要使用buf
buf[j * width + i];
另一种创建矩阵的方法(来自评论,感谢James Kanze)就是创建缓冲区,如:char (*buf)[20000] = new char[20000][200000]
。在这种情况下,访问缓冲区就像:buf[i][j]
最安全的方法是使用std :: vector或array,并避免使用new / delete。使用std :: vector来防止缓冲区写溢出:
clock_t RowMajor()
{
int width = 20000;
int height = 20000;
std::vector<char> buf;
buf.resize(width * height);
clock_t start = clock();
for (int j = 0; j <height; j++)
for (int i = 0; i <width; i++)
{
++buf[i + j * width];
}
clock_t elapsed = clock() - start;
return elapsed;
}
答案 1 :(得分:0)
感谢Raxvan,这是最终的代码到目前为止工作正常
#include <iostream>
#include <time.h>
#include <cstdio>
#include <windows.h>
int calc = 0;
clock_t RowMajor()
{
int width = 20000;
int height = 20000;
char* buf = new char[width * height];
clock_t start = clock();
for (int j = 0; j < height; j++)
for (int i = 0; i < width; i++)
{
++buf[i + width * j];
}
clock_t elapsed = clock() - start;
delete[] buf;
return elapsed;
}
clock_t ColumnMajor()
{
int width = 20000;
int height = 20000;
char* buf = new char[width * height];
clock_t start = clock();
for (int j = 0; j < height; j++)
for (int i = 0; i < width; i++)
{
++buf[j + width * i];
}
clock_t elapsed = clock() - start;
delete[] buf;
return elapsed;
}
int main()
{
std::cout << "Process Started." << std::endl;
calc= ColumnMajor() /CLOCKS_PER_SEC ;
printf( "ColumnMajor took %lu . \n", calc );
calc=RowMajor()/CLOCKS_PER_SEC ;
printf( "RowMajor took %lu . \n", calc );
std::cout << "done" << std::endl; return 0;
}