什么是图像阵列中最快的数组填充

时间:2013-10-26 01:05:29

标签: c algorithm padding

所以我在1D中有一个图像数组:

a = {1,2,3,4,5,6,7,8,9}

使用zeoes进行数组填充以围绕它的最快方法是什么:

0 0 0 0 0
0 1 2 3 0
0 4 5 6 0
0 7 8 9 0
0 0 0 0 0

我已经声明了b数组(它是a的填充数组):

float *b = calloc(((data_size_X + 2)*(data_size_Y +2)), sizeof(float));

2 个答案:

答案 0 :(得分:2)

这是一些基准测试。我的预感是对的 - 使用memcpy明显快于替代方案:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
  char* original;
  char* padded;
  long int n, m, ii, jj, kk;
  time_t startT, stopT;

  char *p1, *o1; //  point to first element in row for padded, original

  // pick a reasonably sized image:
  n = 3000;
  m = 2000;

  // allocate memory:
  original = malloc(m * n * sizeof(char));
  padded = calloc((m+2)*(n+2), sizeof(char));

  // put some random values in it:
  for(ii = 0; ii < n*m; ii++) {
    original[ii] = rand()%256;
  }

  // first attempt: completely naive loop
  startT = clock();
  for(kk = 0; kk < 100; kk++) {
    for(ii = 0; ii < m; ii++) {
      for(jj = 0; jj < n; jj++) {
        padded[(ii + 1) * (n + 2) + jj + 1] = original[ ii * n + jj];
      }
    }
  }
  stopT = clock();
  printf("100 loops of 'really slow' took %.3f ms\n", (stopT - startT) * 1000.0 / CLOCKS_PER_SEC);

  // second attempt - pre-compute the index offset
  startT = clock();
  for(kk = 0; kk < 100; kk++) {
    for(ii = 0; ii < m; ii++) {
      p1 = padded + (ii + 1) * (n + 2) + 1;
      o1 = original + ii * n;
      for(jj = 0; jj < n; jj++) {
        p1[jj] = o1[jj];
      }
    }
  }
  stopT = clock();
  printf("100 loops of 'not so fast' took %.3f ms\n", (stopT - startT) * 1000.0 / CLOCKS_PER_SEC);

  // third attempt: use memcpy to speed up the process    
  startT = clock();
  for(kk = 0; kk < 100; kk++) {
    for(ii = 0; ii < m; ii++) {
      p1 = padded + (ii + 1) * (n + 2) + 1;
      o1 = original + ii * n;
      memcpy(p1, o1, n);
    }
   }
  stopT = clock();
  printf("100 loops of 'fast' took %.3f ms\n", (stopT - startT) * 1000.0 / CLOCKS_PER_SEC);

  free(original);
  free(padded);
  return 0;
}

以下是结果输出:

100 loops of 'really slow' took 3020.585 ms
100 loops of 'not so fast' took 3725.056 ms
100 loops of 'fast' took 332.298 ms

当我使用-O3启用编译器优化时,时序更改如下:

100 loops of 'really slow' took 2727.442 ms
100 loops of 'not so fast' took 488.244 ms
100 loops of 'fast' took 326.998 ms

显然,编译器“发现”了更清晰的复制循环,并尝试对其进行一些优化 - 但它仍然不如memcpy那样好。在memcpy中几乎没有什么可以优化的。

答案 1 :(得分:0)

如果您已按照描述分配了b,则以下内容可能比嵌套for循环更快:

int aIndex;
int maxA = data_size_X * data_size_Y;
float * pb = b + data_size_X + 3;
memset(b, 0, (data_size_X + 2) * (data_size_Y + 2) * sizeof(float));
for (aIndex = 0; aIndex < maxA;  aIndex += data_sizeX) {
    memcpy(pb, a + aIndex, data_size_X);
    pb += (data_size_X + 2);
}