Chinaunix首页 | 论坛 | 博客
  • 博客访问: 470130
  • 博文数量: 143
  • 博客积分: 6159
  • 博客等级: 准将
  • 技术积分: 1667
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-25 23:08
文章分类

全部博文(143)

文章存档

2013年(1)

2012年(11)

2011年(55)

2010年(76)

分类: C/C++

2011-07-10 10:38:28

最近在作avs优化的时候,有同学问,好奇怪阿,他这个指针要了加个restrict?
把wiki中的restict的解释放到这里:)

In the , as of the , restrict is a that can be used in declarations. The restrict keyword is a declaration of intent given by the programmer to the . It says that for the lifetime of the pointer, only it or a value directly derived from it (such as ​pointer + 1​) will be used to access the object to which it points. This limits the effects of , aiding caching optimizations. If the declaration of intent is not followed and the object is accessed by an independent pointer, this will result in . Optimization

If the compiler knows that there is only one pointer to a memory block, it can produce better code. The following hypothetical example makes it clearer:

  1. void updatePtrs(size_t *ptrA, size_t *ptrB, size_t *val)
  2. {
  3.     *ptrA += *val;
  4.     *ptrB += *val;
  5. }

In the above code, the pointers ptrA, ptrB, and val might refer to the , so the compiler will generate a less optimal code :

  1. load R1 ← *val ; Load the value of val pointer
  2. load R2 ← *ptrA ; Load the value of ptrA pointer
  3. add R2 += R1 ; Perform Addition
  4. set R2 → *ptrA ; Update the value of ptrA pointer
  5. ; Similarly for ptrB, note that val is loaded twice,
  6. ; because ptrA may be equal to val.
  7. load R1 ← *val
  8. load R2 ← *ptrB
  9. add R2 += R1
  10. set R2 → *ptrB

However if the restrict keyword is used and the above function is declared as :

void updatePtrs(size_t *restrict ptrA, size_t *restrict ptrB, size_t *restrict val);

then the compiler is allowed to assume that ptrA, ptrB, and val point to different locations and updating one pointer will not affect the other pointers. The programmer, not the compiler, is responsible for ensuring that the pointers do not point to identical locations.

Now the compiler can generate better code as follows:

  1. load R1 ← *val
  2. load R2 ← *ptrA
  3. add R2 += R1
  4. set R2 → *ptrA
  5. ; Note that val is not reloaded,
  6. ; because the compiler knows it is unchanged
  7. load R2 ← *ptrB
  8. add R2 += R1
  9. set R2 → *ptrB

Note that the above assembly code is shorter because val is loaded once.


阅读(982) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~