gpt4 book ai didi

c++ - 使用 -g 编译本身会降低性能吗?

转载 作者:IT老高 更新时间:2023-10-28 22:39:08 25 4
gpt4 key购买 nike

(这是一个关于 gcc 和 clang 的问题,但可能适用于其他编译器。)

如果我编译我的 C 或 C++ 代码,并使用 -g 开关生成调试信息,这本身是否会以任何方式降低已编译程序的性能...

  1. 最小优化(-O0)?
  2. 最大优化(-O3)?

注意:我并不是指必须解析/加载可执行文件的性能损失,由于额外的内容,性能损失更大;我的意思是运行的代码。

最佳答案

我认为没有任何性能差异。根据文档 here,确实生成的代码是相同的,并且 -g 可以与 -O 一起使用.此外,调试符号不会写入代码中,而是写入另一个称为“调试部分”的部分,甚至在运行时都不会加载(仅由调试器加载)

-g 不会改变运行的优化或生成的代码。这是 here 所述的 gcc 政策

但是,请注意相同的文档指出:

The shortcuts taken by optimized code may occasionally be surprising: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values are already at hand; some statements may execute in different places because they have been moved out of loops. Nevertheless it is possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs.

所以最终调试永远不会影响您的优化,但相反是错误的,使用 -O3 可能会降低您的调试信息(例如通过删除无用的变量)。

请注意,在这种情况下使用 -Og (如 here 所述)可能会更好,因为它会:

Optimize debugging experience. -Og enables optimizations that do not interfere with debugging. It should be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience.

但是这会影响性能,因为不会执行一些会干扰调试的优化过程。


编辑:

链接和引号回答了您对 gcc 的问题。它可能不适用于其他编译器,例如 clang。不过,我也找到了一些关于 clang 的文档。例如 here :

Basically, the debug information allows you to compile a program with “-O0 -g” and get full debug information, allowing you to arbitrarily modify the program as it executes from a debugger. Compiling a program with “-O3 -g” gives you full debug information that is always available and accurate for reading (e.g., you get accurate stack traces despite tail call elimination and inlining), but you might lose the ability to modify the program and call functions where were optimized out of the program, or inlined away completely.

关于c++ - 使用 -g 编译本身会降低性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39222698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com