c++ - 当 GCC 明确表示会减慢程序速度时,为什么要在 O2/O3 处启用优化?

标签 c++ gcc compiler-optimization memory-alignment

<分区>

引自https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html :

-falign-labels

-falign-labels=n

Align all branch targets to a power-of-two boundary, skipping up to n bytes like -falign-functions. This option can easily make code slower, because it must insert dummy operations for when the branch target is reached in the usual flow of the code.

-fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.

If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.

If n is not specified or is zero, use a machine-dependent default which is very likely to be ‘1’, meaning no alignment.

Enabled at levels -O2, -O3.

更多地考虑这个标志会使它失去更多的意义......引发代码缓存未命中的后果,以及当参数采用数值 (1..) 时甚至启用意味着什么?

最佳答案

不是这么说的。它说可以很容易地使代码变慢。这意味着,在某些情况下,它会使代码变慢。在其他情况下,它可以使代码更快。

对齐导致代码运行速度变慢:

  • 增加代码大小,因此代码不在缓存中的可能性更高。
  • 添加了nop操作减慢代码

对齐可以使代码运行得更快:分支预测、指令获取和天知道什么。

在单个if的情况下,很难说哪个效果更强。这取决于条件。

但是,对于一个循环,通常代码会变得更快。为什么?因为慢因素只发生一次,但循环的每个循环都会执行得更快。

(我的 GCC 似乎将标签对齐到 8)

关于c++ - 当 GCC 明确表示会减慢程序速度时,为什么要在 O2/O3 处启用优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990306/

相关文章:

c - 为什么使用 GCC 5 和 cilk-plus 会出现此编译错误?

c - c 编译器是否可以将 'if-elseif' block 转换为 'switch' block 以优化代码?

c++ - 具有已删除方法的 C++ 类是否可以轻松复制?

c++ - 链接 qt5 库通过 cmake 自动将额外的 fPIcflags传递给 nvcc 编译器,导致错误

c++ - OpenGL:准备要发送给着色器的数据困惑

c++ - g++,当我不使用异常时的异常成本

c++ - 使用 C++ 在 RHEL 7 上接收多播数据

c++ - GCC 和 NVCC 之间的代码共享

c++ - 是什么阻止了编译器对强异常安全代码重新排序的优化?

c++ - 指向堆栈变量的指针应该是易变的吗?