gpt4 book ai didi

c++ - 不同编译器中的纯/常量函数属性

转载 作者:IT老高 更新时间:2023-10-28 12:41:45 25 4
gpt4 key购买 nike

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 < C; ++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 < C; ++i)
sum += temp;
return sum;
}

或者如果你的编译器足够聪明(并且对 float 没有那么严格):

float calculate(float x, unsigned int C) { return C ? sigmoid(x) * C : 0.0f; }

如何为不同的编译器(即 GCC、Clang、ICC、MSVC 或其他)以这种方式标记函数?

最佳答案

一般来说,似乎几乎所有的编译器都支持 GCC 属性。 MSVC 是迄今为止唯一不支持它们的编译器(也没有任何替代方案)。

关于c++ - 不同编译器中的纯/常量函数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2798188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com