[英]GCC compile-time floating point optimization
I'm developing for the AVR platform and I have a question. 我正在为AVR平台开发,但有一个问题。 I don't want the floating point library to be linked with my code, but I like the concept of having analog values of the range 0.0 ... 1.0 instead of 0...255 and 0...1023, depending on even whether I'm using a port as an input or as an output.
我不希望将浮点库与我的代码链接,但是我喜欢这样的概念:模拟值范围为0.0 ... 1.0,而不是0 ... 255和0 ... 1023,具体取决于我使用端口作为输入还是输出。
So I decided to multiply the input/output functions' arguments by 1023.0 and 255.0, respecively. 因此,我决定将输入/输出函数的参数分别乘以1023.0和255.0。 Now, my question is: if I implement the division like this:
现在,我的问题是:如果我像这样实现除法:
#define analog_out(port, bit) _analog_out(port, ((uint8_t)((bit) * 255.0)))
will GCC (with the -O3 flag turned on) optimize the compile-time floating point multiplications, known at compile time and cast to an integral type, into integer operations? GCC(将-O3标志打开)是否会优化编译时浮点乘法(在编译时已知并转换为整数类型)进行整数运算? (I know that when using these macros with non-constant arguments, the optimization is not possible; I just want to know if it will be done in the other case.)
(我知道,当将这些宏与非恒定参数一起使用时,优化是不可能的;我只想知道在其他情况下是否可以这样做。)
GCC should always do constant folding if you supply bit as a numeric literal. 如果您提供bit作为数字文字,那么GCC应该始终进行恒定折叠。 If you want the compiler enforce the constness, you could get away with something like this:
如果您希望编译器强制执行constness,则可以避免以下情况:
#define force_const(x) (__builtin_choose_expr(__builtin_constant_p(x), (x), (void)0))
#define analog_out(port, bit) _analog_out(port, force_const((uint8_t)((bit) * 255.0)))
Generally, I think gcc -O2
will do all arithmetic on constants at compile time. 通常,我认为
gcc -O2
将在编译时对常量进行所有算术运算。
It won't convert it to integer arithmetic - just to a constant integer. 它不会将其转换为整数运算-只会转换为常数整数。
It may be dangerous to rely on, especially if other people maintain the code. 依靠它可能很危险,尤其是在其他人维护代码的情况下。 A situation where passing a non-constant parameter to a macro results in an error isn't good.
将非常量参数传递给宏会导致错误的情况不是很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.