如何告诉c++编译器对象没有在其他地方被改变以达到更好的优化
How to tell c++ compiler that the object is not changed elsewhere to reach better optimization
我想优化一些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相关文章:
- 空基优化子对象的地址
- 变量没有改变?通过向量的函数调用
- 关闭||运算符优化
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 返回值优化:显式移动还是隐式
- 人脸跟踪arduino代码的优化
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 如何改变c++应用程序的视觉效果
- 纯函数,为什么没有优化
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- C++在不同线程中改变向量
- 如何以优化的方式同时迭代两个间距不相等的数组
- 如何访问和改变存储在矢量C++中的对象
- 小字符串优化(调试与发布模式)
- 浮点定向舍入和优化
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- G++和__attribute__((优化))不改变调试器行为
- 是否有任何优化选项,可以改变结构的对齐在VS2012
- 告诉gcc优化器值在全局函数中改变了
- 如何告诉c++编译器对象没有在其他地方被改变以达到更好的优化