pure / const函数属性在不同的编译器 [英] pure/const function attributes in different compilers
问题描述
pure 是一个函数属性,它说函数不会修改任何全局内存。
const 是一个函数属性,函数不读/修改任何全局内存。
编译器可以做一些额外的优化。
GCC的示例:
float sigmoid(float x)__attribute__((const));
float calculate(float x,unsigned int C){
float sum = 0;
for(unsigned int i = 0; i sum + = sigmoid(x);
return sum;
}
float sigmoid(float x){return 1.0f /(1.0f - exp(-x)); }
在该示例中,编译器可以优化函数 calculate
float calculate(float x,unsigned int C){
float sum = 0;
float temp = C? sigmoid(x):0.0f;
for(unsigned int i = 0; i sum + = temp;
return sum;
}
或者如果你的编译器足够聪明
float calculate(float x,unsigned int C){return C? sigmoid(x)* C:0.0f;如何用不同的编译器标记一个函数,例如GCC,Clang,ICC? ,MSVC或其他?解决方案
- GCC: pure/const函数属性
- llvm-gcc:支持GCC pure / const属性
- Clang:似乎支持它(我试过一个简单的例子与GCC样式属性,它工作。)
- ICC: a href =http://software.intel.com/en-us/forums/showthread.php?t=62309>似乎采用GCC属性(抱歉,只有论坛帖子。)
-
- MSVC:似乎不支持它。 (讨论)
一般来说,几乎所有编译器都支持GCC属性。 MSVC是迄今为止唯一不支持它们的编译器(也没有任何替代)。
pure is a function attribute which says that a function does not modify any global memory.
const is a function attribute which says that a function does not read/modify any global memory.
Given that information, the compiler can do some additional optimisations.
Example for GCC:
float sigmoid(float x) __attribute__ ((const));
float calculate(float x, unsigned int C) {
float sum = 0;
for(unsigned int i = 0; i < C; ++i)
sum += sigmoid(x);
return sum;
}
float sigmoid(float x) { return 1.0f / (1.0f - exp(-x)); }
In that example, the compiler could optimise the function calculate to:
float calculate(float x, unsigned int C) {
float sum = 0;
float temp = C ? sigmoid(x) : 0.0f;
for(unsigned int i = 0; i < C; ++i)
sum += temp;
return sum;
}
Or if your compiler is clever enough (and not so strict about floats):
float calculate(float x, unsigned int C) { return C ? sigmoid(x) * C : 0.0f; }
How can I mark a function in such way for the different compilers, i.e. GCC, Clang, ICC, MSVC or others?
解决方案
- GCC: pure/const function attributes
- llvm-gcc: supports the GCC pure/const attributes
- Clang: seems to support it (I tried on a simple example with the GCC style attributes and it worked.)
- ICC: seems to adopt the GCC attributes (Sorry, only a forum post.)
- MSVC: Seems not to support it. (discussion)
In general, it seems that almost all compilers support the GCC attributes. MSVC is so far the only compiler which does not support them (and which also doesn't have any alternative).
这篇关于pure / const函数属性在不同的编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!