st*************@hotmail.com wrote:
Hi!
I would appreciate some help with this (basic) question. I need to
copy an 2D array x to another 2D array y. I know how to do it copying
element by element, but I would like to use a faster method (because I
have to do many many copies). Can anyone tell me a faster method (one
who thak's less time running)? Thanks.
I'm using the following method:
----------------------------------------
int
x[3][3] = {{0,1,2},{3,4,5},{6,7,8}},
y[3][3],
i, j;
int main()
{
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
y[i][j] = x[i][j];
return 0;
}
----------------------------------------
Optimization is system dependant so to get the best possible answer, you
need to tune it to your system. Here are all the alternatives, you
choose the one which runs fastest on your system.
template <typename T, int Rows, int Cols>
void MatrixCopy(
T (&Dest)[Rows][Cols],
const T (&Src)[Rows][Cols]
) {
T * Destp = & Dest[0][0];
const T * Srcp = & Src[0][0];
const int count = Rows * Cols;
for ( int i = 0; i < count; ++ i )
{
* ( Destp ++ ) = * (Srcp ++ );
}
}
Or
template <typename T, int Rows, int Cols>
void MatrixCopy(
T (&Dest)[Rows][Cols],
const T (&Src)[Rows][Cols]
) {
T * Destp = & Dest[0][0];
const T * Srcp = & Src[0][0];
const int count = Rows * Cols;
for ( int i = 0; i < count; ++ i )
{
Destp[ i ] = Srcp[ i ];
}
}
or
template <typename T, int Rows, int Cols>
void MatrixCopy(
T (&Dest)[Rows][Cols],
const T (&Src)[Rows][Cols]
) {
T * Destp = & Dest[0][0];
const T * Srcp = & Src[0][0];
const int count = Rows * Cols;
memcpy(
static_cast< void * >( Destp ),
static_cast< const void * >( Src ),
sizeof( Dest )
);
}
or
template <typename T>
void MatrixCopy(
T (&Dest)[3][3],
const T (&Src)[3][3]
) {
T * Destp = & Dest[0][0];
const T * Srcp = & Src[0][0];
register T v0 = Src[0][0];
register T v1 = Src[0][1];
register T v2 = Src[0][2];
register T v3 = Src[1][0];
register T v4 = Src[1][1];
register T v5 = Src[1][2];
register T v6 = Src[2][0];
register T v7 = Src[2][1];
register T v8 = Src[2][2];
Dest[0][0] = v0;
Dest[0][1] = v1;
Dest[0][2] = v2;
Dest[1][0] = v3;
Dest[1][1] = v4;
Dest[1][2] = v5;
Dest[2][0] = v6;
Dest[2][1] = v7;
Dest[2][2] = v8;
}