有没有办法判断是否已使用优化参数编译C#程序集?

Joh*_*ohn 10 c# optimization assemblies

相反,有没有办法告诉它是否已启用或禁用优化参数编译.我不想知道它是发布还是调试,因为可以使用或不使用优化来启用它们.从我的角度来看,即使代码说它是发布版本,它是否真正优化了?谢谢.

Jar*_*Par 9

检查的一种方法是查看程序集上的DebuggableAttribute(doc).DisableOptimizations如果C#编译器通过了/ optimize选项,则不会设置该标志.

注意:虽然这适用于大多数情况,但这不是100%万无一失的解决方案.至少可以通过以下方式打破它

  1. 使用具有不同语义的另一种语言进行编译以进行优化
  2. 如果用户手定义DebuggableAttribute它将优先于C#编译器定义的内容


Han*_*ant 6

使用Ildasm.exe查看程序集清单:

  // --- The following custom attribute is added automatically, do not uncomment -------
  //  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(
          valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) 
          = ( 01 00 02 00 00 00 00 00 ) 
Run Code Online (Sandbox Code Playgroud)

那是Release版本.调试版本值为(01 00 07 01 00 00 00 00)

另一个问题是调试器可以禁用JIT优化器.这是VS,Tools + Options,Debugging,General中的可配置选项,"抑制模块加载时的JIT优化".如果您正在调试Release版本并希望获得类似的性能,那么您希望这样做.它使调试更具挑战性,当优化器重新排列和内联代码时,步进行为很奇怪,因为它们存储在CPU寄存器中,所以通常无法检查局部变量的值.


Bru*_*cia 6

我迟到了 8 年,但如果你像我一样想要 C# 方式,这里是:

using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;

internal static class AssemblyExtensions
{
    public static bool IsOptimized(this Assembly asm)
    {
        var att = asm.GetCustomAttribute<DebuggableAttribute>();
        return att == null || att.IsJITOptimizerDisabled == false;
    }
}
Run Code Online (Sandbox Code Playgroud)

作为扩展方法:

static void Main(string[] args)
{
    Console.WriteLine("Is optmized: " + typeof(Program).Assembly.IsOptimized());
}
Run Code Online (Sandbox Code Playgroud)