可以C ++编译器优化“if” “for”中的语句循环? [英] Can C++ compilers optimize "if" statements inside "for" loops?

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

问题描述

请考虑这样的示例:

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

如果标志 for 循环,这在语义上应该等同于:

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

只有在第一种情况下,代码可能会更长> 使用循环,或 do_something()是一个大体与 do_something_else



我很好奇当前的C ++编译器(最重要的是g ++)能够优化第二个例子来摆脱 for 循环中的重复测试。

是的,如果确定标志没有改变,并且可以'改变' t可以通过do_something或do_something_else来改变,它可以被拉到循环之外。我听说过这种称为循环提升,但维基百科有一个名为循环不变代码运动的条目



如果flags是一个局部变量,编译器应该能够做这个优化,因为它保证对生成的代码的行为没有影响。



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



这也会受到您所做的优化的影响 - 优化大小会有利于非提升版本,而优化速度可能会有利于提升版本。 / p>

一般来说,这不是你应该担心的事情,除非profiling告诉你这个函数是一个热点,你看到效率低的代码实际上是通过编译器输出的汇编来生成的。像这样的微优化,你应该总是留给编译器,除非你绝对需要。


Consider an example like this:

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

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();

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.

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?

解决方案

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".

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.

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”中的语句循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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