简体   繁体   English

编译器优化,划分宏扩展

[英]Compiler optimizations, divide macro expansions

I have following piece of code, 我有以下一段代码,

Scenario 1 场景1

/* get count of elements in an array */
#define COUNT(x)         sizeof(x)/sizeof(x[0])

struct Data data[] = {/* some data goes here */};

int count = COUNT(data);

Scenario 2 情景2

#define TOTAL            32
#define EACH              4
int count = (TOTAL/EACH)

I know macros are resolved during preprocessing and sizeof is a compile time operator, but what about the division: does it get optimised during compilation ? 我知道宏在预处理期间被解析,而sizeof是一个编译时运算符,但是除法如何:它在编译期间是否得到优化?

Is there any tool to see the optimizations done by the compiler ? 有没有工具可以看到编译器完成的优化?

Usually you can let the compiler show you the generated assembly code. 通常,您可以让编译器显示生成的汇编代码。 With Visual C++ you can do that with the /Fa<file> option. 使用Visual C ++,您可以使用/Fa<file>选项执行此操作。 gcc has the -S option. gcc-S选项。

As for your question: Most compilers should precompute constant expressions, at least at optimisation levels higher than O0 . 至于你的问题:大多数编译器应该预先计算常量表达式,至少在高于O0优化级别。

Let's see with your example scenarios: 让我们看看您的示例场景:

#define COUNT(x)         sizeof(x)/sizeof(x[0])
int data[] = {1, 2, 3, 4, 5};
int count = COUNT(data);

Compiled with cl /c /Fascenario1.asm scenario1.c yields: cl /c /Fascenario1.asm scenario1.c编译得到:

...
PUBLIC  _data
PUBLIC  _count
_DATA   SEGMENT
_data   DD  01H
    DD  02H
    DD  03H
    DD  04H
    DD  05H
_count  DD  05H
_DATA   ENDS
END

You see the value for count close to the end, and it's indeed 5. So the compiler computed the value even with no optimisation turned on. 你看到count的值接近结尾,而且确实是5.所以即使没有打开优化,编译器也会计算出该值。

Your second scenario: 你的第二个场景:

#define TOTAL            32
#define EACH              4
int count = (TOTAL/EACH);

yields 产量

...
PUBLIC  _count
_DATA   SEGMENT
_count  DD  08H
_DATA   ENDS
END

where the expression was precomputed as well. 表达式也是预先计算的。

It's not uncommon at higher optimisation levels for the compiler to even evalute more complex expressions when you pass compile-time constants. 在更高的优化级别上,编译器在传递编译时常量时甚至可以评估更复杂的表达式,这种情况并不少见。 As an example, I once looked at the code of three different ways of swapping two integers and once I turned optimisation on the compiler simply threw out the call to the swap method entirely, replacing the arguments to my test printf with the already-swapped values. 作为一个例子,我曾经看过交换两个整数的三种不同方式的代码,一旦我对编译器进行优化,只需完全抛出对swap方法的调用,用已交换的值替换我的test printf的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM