是否有人在gcc/g++实际上中使用C/C++ restrict关键字是否在实际中(而不只是理论上)显着提高了性能?

我读过很多有关推荐/贬低其用法的文章,但是我还没有碰到任何实际数字来证明双方的观点。

编辑

我知道restrict并不是C++的正式组成部分,但是某些编译器支持ojit_code,我已经阅读了Christer Ericson的一篇论文,强烈建议其用法。

最佳答案

limit关键字有所不同。

在某些情况下(图像处理),我看到了因子2甚至更高的改进。大多数情况下,差异并不大。大约10%。

这是一个说明差异的小例子。我已经写了一个非常基本的4x4 vector *矩阵变换作为测试。请注意,我必须强制不要内联函数。否则,GCC会检测到我的基准代码中没有任何别名指针,并且由于内联,限制不会产生任何影响。

我也可以将转换功能移到另一个文件中。

#include <math.h>

#ifdef USE_RESTRICT
#else
#define __restrict
#endif


void transform (float * __restrict dest, float * __restrict src,
                float * __restrict matrix, int n) __attribute__ ((noinline));

void transform (float * __restrict dest, float * __restrict src,
                float * __restrict matrix, int n)
{
  int i;

  // simple transform loop.

  // written with aliasing in mind. dest, src and matrix
  // are potentially aliasing, so the compiler is forced to reload
  // the values of matrix and src for each iteration.

  for (i=0; i<n; i++)
  {
    dest[0] = src[0] * matrix[0] + src[1] * matrix[1] +
              src[2] * matrix[2] + src[3] * matrix[3];

    dest[1] = src[0] * matrix[4] + src[1] * matrix[5] +
              src[2] * matrix[6] + src[3] * matrix[7];

    dest[2] = src[0] * matrix[8] + src[1] * matrix[9] +
              src[2] * matrix[10] + src[3] * matrix[11];

    dest[3] = src[0] * matrix[12] + src[1] * matrix[13] +
              src[2] * matrix[14] + src[3] * matrix[15];

    src  += 4;
    dest += 4;
  }
}

float srcdata[4*10000];
float dstdata[4*10000];

int main (int argc, char**args)
{
  int i,j;
  float matrix[16];

  // init all source-data, so we don't get NANs
  for (i=0; i<16; i++)   matrix[i] = 1;
  for (i=0; i<4*10000; i++) srcdata[i] = i;

  // do a bunch of tests for benchmarking.
  for (j=0; j<10000; j++)
    transform (dstdata, srcdata, matrix, 10000);
}

结果:(在我的2 Ghz Core Duo上)
nils@doofnase:~$ gcc -O3 test.c
nils@doofnase:~$ time ./a.out

real    0m2.517s
user    0m2.516s
sys     0m0.004s

nils@doofnase:~$ gcc -O3 -DUSE_RESTRICT test.c
nils@doofnase:~$ time ./a.out

real    0m2.034s
user    0m2.028s
sys     0m0.000s

在该系统上,拇指执行速度提高了20%。

为了显示它在多大程度上取决于体系结构,我让相同的代码在Cortex-A8嵌入式CPU上运行(略微调整了循环计数,因为我不想等待那么长时间):
root@beagleboard:~# gcc -O3 -mcpu=cortex-a8 -mfpu=neon -mfloat-abi=softfp test.c
root@beagleboard:~# time ./a.out

real    0m 7.64s
user    0m 7.62s
sys     0m 0.00s

root@beagleboard:~# gcc -O3 -mcpu=cortex-a8 -mfpu=neon -mfloat-abi=softfp -DUSE_RESTRICT test.c
root@beagleboard:~# time ./a.out

real    0m 7.00s
user    0m 6.98s
sys     0m 0.00s

这里的差异仅为9%(相同的编译器顺便说一句)。

关于c++ - limit关键字在gcc/g++中是否具有明显的优势?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1965487/

10-12 05:24