GCC:-O3 和 -Os 之间的区别

2022-01-17 00:00:00 gcc c g++ compiler-construction c++

我对 GCC -O3 标志非常熟悉,但它与 -Os 有何不同,在哪种情况下我们应该更喜欢一个而不是另一个?

I am quite familiar with GCC -O3 flag, but how it differs from -Os, in which situation we should prefer one over other?

推荐答案

GCC 文档非常明确地描述了这些选项的作用.

The GCC documentation describes what these options do very explicitly.

-O3 尝试大量优化代码以提高性能.它包括所有优化 -O2 包括,以及更多.

-O3 tries to optimize code very heavily for performance. It includes all of the optimizations -O2 includes, plus some more.

-Os 指示 GCC 优化大小".它启用所有 -O2 优化不会增加可执行文件的大小,然后它还会切换一些优化标志以进一步减小可执行文件的大小.

-Os, on the other hand, instructs GCC to "optimize for size." It enables all -O2 optimizations which do not increase the size of the executable, and then it also toggles some optimization flags to further reduce executable size.

请注意,我的描述故意含糊不清 - 请阅读 GCC 文档以更深入地讨论究竟为任一优化级别启用了哪些标志.

Note that I've been deliberately a bit vague with my descriptions - read the GCC documentation for a more in-depth discussion of exactly which flags are enabled for either optimization level.

我相信 -O* 优化级别就是 - 互斥、不同的优化级别.混合它们并没有真正的意义,因为两个级别将启用或忽略另一个级别有意忽略或启用的标志(分别).如果你想混合和匹配(你可能实际上不想这样做,除非你有一个非常好的理由想要一组特定的标志),你最好阅读文档并混合和匹配每个级别的标志手动启用.

I believe the -O* optimization levels are just that - mutually exclusive, distinct levels of optimization. It doesn't really make sense to mix them, since two levels will enable or leave out flags that the other one intentionally leaves out or enables (respectively). If you want to mix and match (you probably don't actually want to do this, unless you have a really good reason to want a specific set of flags), you are best off reading the documentation and mixing and matching the flags each level enables by hand.

我想我还会从 Gentoo Linux Wiki 链接 这篇文章,其中讨论了相关的优化标志为操作系统构建软件包.显然,并非所有这些都适用,但它仍然包含一些有趣的信息――例如:

I think I'll also link this article from the Gentoo Linux Wiki, which talks about optimization flags as they relate to building the packages for the operating system. Obviously not all of this is applicable, but it still contains some interesting information - for one:

使用 -O3 编译并不是提高性能的保证方法,事实上,在许多情况下,由于二进制文件较大和内存使用量增加,可能会降低系统速度.-O3 也可以破坏多个包裹.所以不推荐使用-O3.

Compiling with -O3 is not a guaranteed way to improve performance, and in fact in many cases can slow down a system due to larger binaries and increased memory usage. -O3 is also known to break several packages. Therefore, using -O3 is not recommended.

根据那篇文章,在大多数情况下,-O2 与 -O3 一样好",并且在可执行输出损坏方面使用起来更安全.

According to that article, -O2 is, most of the time, "as good as" -O3, and is safer to use, regarding broken executable output.

相关文章