pure / const函数属性在不同的编译器 [英] pure/const function attributes in different compilers

查看:279
本文介绍了pure / const函数属性在不同的编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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属性。 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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆