我正在做一个旋转二维数组的项目。当我使用宏替换一些代码时,结果令人惊讶,因为一切都完全一样。完成任务所需的时间可能会有很大不同。我一直认为宏只是一个占位符,但这怎么可能发生呢?
struct pixel
{
unsigned short red;
unsigned short green;
unsigned short blue;
} ;
//n is the # of elements in the two dimensional array
void rotate1(int n, pixel *src, pixel *dst)
{
int row, col, max = n - 1;
for (row = 0; row < n; row++)
for (col = 0; col < n; col++)
*(dst+ (((max - row)*n)+col)) = *(src+ (row*n + col));
}
void rotate11(int n, pixel *src, pixel *dst)
{
#define TARGET *(dst + (((max - row)*n)+col))
#define SOURCE *(src + (row*n + col))
int row, col, max = n - 1;
for (row = 0; row < n; row++)
for (col = 0; col < n; col++)
{
TARGET = SOURCE;
}
}
结果是:
Time= 2.25 n= 512 Method= rotate1
Time= 2.18 n= 512 Method= rotate11
Time= 8.05 n= 1024 Method= rotate1
Time= 8.08 n= 1024 Method= rotate11
Time= 25.18 n= 2048 Method= rotate1
Time= 25.24 n= 2048 Method= rotate11
Time= 104.38 n= 4096 Method= rotate1
Time= 104.21 n= 4096 Method= rotate11
Time= 1272.41 n= 8192 Method= rotate1
Time= 423.00 n= 8192 Method= rotate11
当 n 较小时,两者具有相似的性能,但随着 n 变得越来越大,所rotate11
花费的时间越来越少。