做任何C或C ++编译器优化中定义的宏? [英] Do any C or C++ compilers optimize within define macros?

查看:134
本文介绍了做任何C或C ++编译器优化中定义的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我在下面的 C 或C ++:

Let's say I have the following in C or C++:

#include <math.h>
#define ROWS 15
#define COLS 16
#define COEFF 0.15
#define NODES (ROWS*COLS)
#define A_CONSTANT (COEFF*(sqrt(NODES)))

然后,我去用节点 A_CONSTANT 地方内的许多嵌套循环深(即多次使用) 。显然,两者都有可在编译时确定的数值,但实际上编译器做呢?在运行时,将CPU必须评估 15 * 16 每次看到时间节点,或将编译器静态放 240 吗?同样,将CPU有每次看到时间来评估一个平方根 A_CONSTANT

Then, I go and use NODES and A_CONSTANT somewhere deep within many nested loops (i.e. used many times). Clearly, both have numeric values that can be ascertained at compile-time, but do compilers actually do it? At run-time, will the CPU have to evaluate 15*16 every time it sees NODES, or will the compiler statically put 240 there? Similarly, will the CPU have to evaluate a square root every time it sees A_CONSTANT?

我的猜测是, ROWS * COLS 乘法优化掉了,但没有别的。整数乘法内置于语言,但开方是一个库函数。如果事实确实如此,有没有什么办法让一个神奇相当于数 A_CONSTANT 这样的平方根是在运行时只计算一次?

My guess is that the ROWS*COLS multiplication is optimized out but nothing else is. Integer multiplication is built into the language but sqrt is a library function. If this is indeed the case, is there any way to get a magic number equivalent to A_CONSTANT such that the square root is evaluated only once at run-time?

推荐答案

这取决于你的编译器。

#include <math.h>

#define FOO sqrt(5);

double
foo()
{
  return FOO;
}

我的编译器(gcc 4.1.2)生成以下装配此code:

My compiler (gcc 4.1.2) generates the following assembly for this code:

.LC0:
    .long   2610427048
    .long   1073865591
    .text
    .p2align 4,,15
.globl foo
    .type   foo, @function
foo:
.LFB2:
    movsd   .LC0(%rip), %xmm0
    ret
.LFE2:

所以它不知道的sqrt(5)是一个编译时间常数。

如果你的编译器是没有那么聪明,我不知道有任何的移动的方式来计算平方根在编译时。 (当然,你可以计算出结果后,保存在全球也好,但不是一回事编译时间常数。)

If your compiler is not so smart, I do not know of any portable way to compute a square root at compile time. (Of course, you can compute the result once and store it in a global or whatever, but that is not the same thing as a compile-time constant.)

这篇关于做任何C或C ++编译器优化中定义的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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