如何告诉c++编译器对象没有在其他地方被改变以达到更好的优化

How to tell c++ compiler that the object is not changed elsewhere to reach better optimization

本文关键字:改变 优化 更好 编译器 c++ 何告诉 对象 其他      更新时间:2023-10-16

我想优化一些c++代码。让我们看一个简单的例子:

int DoSomeStuff(const char* data)
{
  while(data != NULL)
  {
    //compute something and use optimization as much as possible
  }
  return result;
}

我知道*data在其他地方没有改变。我的意思是它不会在其他线程中改变,但是编译器无法知道。是否有某种方法可以告诉编译器指针上的数据在作用域的整个生命周期内都不会更改?

更新:

int DoSomeStuff(const volatile char* data)
{
  while(data != NULL)
  {
    //compiler should assume that the data are changed elsewhere
  }
  return result;
}

1)如果变量是const,编译器会优化吗?

根据标准(7.1.6.1):

A pointer or reference to a cv-qualified type need not actually point or refer
to a cv-qualified object, but it is treated as if it does

所以我理解为:编译器将优化对const限定变量的所有访问,就好像它真的是一个const数据,不能通过非const变量的路径进行修改。

2)编译器不会优化以保护线程间访问吗?

根据标准(1.10):

The execution of a program contains a data race if it contains two conflicting
actions in different threads, at least one of which is not atomic, and neither
happens before the other. Any such data race results in undefined behavior.

冲突动作定义为:

Two expression evaluations conflict if one of them modifies a memory location
(1.7) and the other one accesses or modifies the same memory location.

happens-before关系很复杂,但据我所知,除非您在代码中显式使用原子操作(或互斥锁),否则从两个线程(一个写,另一个读/写)访问相同的变量是未定义的行为。这种情况是未定义的行为我不认为编译器会保护你,它是自由的优化。

3)挥发性?

Volatile被设计为防止优化(7.1.6.1):

volatile is a hint to the implementation to avoid aggressive optimization
involving the object because the value of the object might be changed by means
undetectable by an implementation

考虑一个内存映射的I/O寄存器(像一个特殊的输入端口)。即使你不能写它(因为你的硬件实现是只读的),你也不能优化你的读访问(因为它们每次都会返回一个不同的字节)。这个特殊的I/O端口可以是一个温度传感器。

编译器已经允许假定*data没有被另一个线程修改。修改一个线程中的数据并在没有适当同步的情况下在另一个线程中访问它是未定义行为。编译器完全可以对包含未定义行为的程序做任何事情。

我想你的意思是它在其他任何地方都没有别名

在MSVC中可以这样做:

int DoSomeStuff(const char* __restrict  data)
{
  while(data != NULL)
  {
    //compute something and use optimization as much as possible
  }
  return result;
}

:

http://msdn.microsoft.com/en-us/library/5ft82fed.aspx