C++ 编译器可以优化“if"吗?“for"中的语句循环?

Can C++ compilers optimize quot;ifquot; statements inside quot;forquot; loops?(C++ 编译器可以优化“if吗?“for中的语句循环?)

本文介绍了C++ 编译器可以优化“if"吗?“for"中的语句循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个这样的例子:

if (flag)
  for (condition)
    do_something();
else
  for (condition)
    do_something_else();

如果 flagfor 循环内没有改变,这在语义上应该等同于:

If flag doesn't change inside the for loops, this should be semantically equivalent to:

for (condition)
  if (flag)
    do_something();
  else
    do_something_else();

仅在第一种情况下,代码可能会更长(例如,如果使用了多个 for 循环,或者如果 do_something() 是一个几乎相同的代码块到 do_something_else()),而在第二种情况下,标志会被检查多次.

Only in the first case, the code might be much longer (e.g. if several for loops are used or if do_something() is a code block that is mostly identical to do_something_else()), while in the second case, the flag gets checked many times.

我很好奇当前的 C++ 编译器(最重要的是 g++)是否能够优化第二个示例以摆脱 for 循环内的重复测试.如果可以,在什么条件下可能?

I'm curious whether current C++ compilers (most importantly, g++) would be able to optimize the second example to get rid of the repeated tests inside the for loop. If so, under what conditions is this possible?

推荐答案

是的,如果确定flag没有变化,也不能被do_something或do_something_else改变,就可以拉到循环外.我听说过这种称为循环提升的方法,但 Wikipedia 有一个 条目 称为循环不变代码运动"".

Yes, if it is determined that flag doesn't change and can't be changed by do_something or do_something_else, it can be pulled outside the loop. I've heard of this called loop hoisting, but Wikipedia has an entry called "loop invariant code motion".

如果 flags 是一个局部变量,编译器应该能够进行这种优化,因为它保证不会影响生成代码的行为.

If flags is a local variable, the compiler should be able to do this optimization since it's guaranteed to have no effect on the behavior of the generated code.

如果 flags 是全局变量,并且您在循环中调用函数,它可能不会执行优化 - 它可能无法确定这些函数是否修改了全局变量.

If flags is a global variable, and you call functions inside your loop it might not perform the optimization - it may not be able to determine if those functions modify the global.

这也可能会受到您所做的优化类型的影响 - 优化大小将有利于非提升版本,而优化速度可能有利于提升版本.

This can also be affected by the sort of optimization you do - optimizing for size would favor the non-hoisted version while optimizing for speed would probably favor the hoisted version.

一般来说,这不是您应该担心的事情,除非分析告诉您该函数是一个热点,并且您发现实际上是通过检查编译器输出的程序集生成的效率较低的代码.除非绝对必要,否则您应该始终将此类微优化留给编译器.

In general, this isn't the sort of thing that you should worry about, unless profiling tells you that the function is a hotspot and you see that less than efficient code is actually being generated by going over the assembly the compiler outputs. Micro-optimizations like this you should always just leave to the compiler unless you absolutely have to.

这篇关于C++ 编译器可以优化“if"吗?“for"中的语句循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 编译器可以优化“if"吗?“for"中的语句循环?

基础教程推荐