用一维指针好一些还是二维指针好一些?下标运算真的比指针慢?
如题,如果用二维指针表示图像数据,图像中的任何象素可以直接用一个Pixel[y][x]表示,而不必像一维一样pixel[y*iWidth+x],要经过一个加法和乘法才能获得,并且感觉很直观。
在处理图像数据时,每次循环就不需要再计算y*iWidth+x的值了,感觉效率高点。
先看下面这段代码,功能是从宽为src->width,高为src->height的图像数据中截取出宽为out->width,高为out->height的图像数据,而start_x和start_y指的是图像out的左上角点在图像src中的坐标:
for (y = 0; y < out->height; ++y) { for (x = 0; x< out->width; ++x) { /* 计算图片内需要读取的区域的各像素点的位置 */ temp = (start_y + y) * src->width + start_x + x; out->rgba[0][count] = src->rgba[0][temp]; out->rgba[1][count] = src->rgba[1][temp]; out->rgba[2][count] = src->rgba[2][temp]; ++count; } }
for (y = 0; y < out->height; ++y) { for (x = 0; x< out->width; ++x) { xx = start_x + x; yy = start_y + y; out->rgba[0][y][x] = src->rgba[0][yy][xx]; out->rgba[1][y][x] = src->rgba[1][yy][xx]; out->rgba[2][y][x] = src->rgba[2][yy][xx]; } }
out->rgba[0] = (unsigned char **)realloc(out->rgba[0], out->height * sizeof(unsigned char*)); out->rgba[1] = (unsigned char **)realloc(out->rgba[1], out->height * sizeof(unsigned char*)); out->rgba[2] = (unsigned char **)realloc(out->rgba[2], out->height * sizeof(unsigned char*)); for (y = 0; y < out->height; ++y) { out->rgba[0][y] = (unsigned char *)realloc(out->rgba[0][y], out->width * sizeof(unsigned char)); out->rgba[1][y] = (unsigned char *)realloc(out->rgba[1][y], out->width * sizeof(unsigned char)); out->rgba[2][y] = (unsigned char *)realloc(out->rgba[2][y], out->width * sizeof(unsigned char)); }
像这种循环扩大或者减小内存,不仅耗资源,也费时间。一般不会采用这种做法吧.....
图像存成1维的个人感觉速度会好一些,存二维比较直观。
但是按照底层实现上来说个人感觉都是寻址,二维的寻址和你乘法+偏移应该是差不多的(除非二维的寻址,在底层硬件有直接的指令)。
当然,我没有验证过。等高人解答。
[解决办法]
用一维快,因为C++里编译器只认一维,你用二维的话编译器还得转换成一维的
[解决办法]
在循环里面的化,指针大概要快点,每次指针++,但是[n]是每次从头部+n,如果n比较大会有差异,二维的化差异会更大,因为你要乘了再加,而指针直接++