简体   繁体   English

有没有办法让.Net JIT或C#编译器优化掉空的for循环?

[英]Is there a way to get the .Net JIT or C# compiler to optimize away empty for-loops?

A followup to Does .NET JIT optimize empty loops away? .NET JIT是否会优化空循环? :

The following program just runs an empty loop a billion times and prints out the time to run. 以下程序只运行十亿次空循环并打印出运行时间。 It takes 700 ms on my machine, and I'm curious if there's a way to get the jitter to optimize away the empty loop. 我的机器需要700毫秒,我很好奇是否有办法让抖动优化掉空循环。

using System;

namespace ConsoleApplication1 {
    class Program {
        static void Main() {
            var start = DateTime.Now;
            for (var i = 0; i < 1000000000; i++) {}
            Console.WriteLine((DateTime.Now - start).TotalMilliseconds);
        }
    }
}

As far as I can tell the answer is no, but I don't know if there are hidden compiler options I might not have tried. 据我所知,答案是否定的,但我不知道是否有隐藏的编译器选项,我可能没试过。 I have made sure to compile in release mode and run with no debugger attached, but still 700 ms is being taken to run this empty loop. 我确保在发布模式下编译并在没有附加调试器的情况下运行,但仍然需要700毫秒才能运行此空循环。 I also tried NGEN with the same result (though my understanding is that it should produce the same compiled code as the JIT anyway, right?). 我也试过NGEN同样的结果(虽然我的理解是它应该生成与JIT相同的编译代码,对吧?)。 However I've never used NGEN before and may be using it wrong. 但是我之前从未使用过NGEN,可能使用错了。

It seems like this would be something easy for the JIT to find and optimize away, but knowing very little about how jitters work in general, I'm curious if there's a specific reason this optimization would have been left out. 似乎这对JIT来说很容易找到和优化,但是对于一般情况下抖动的工作知之甚少,我很好奇是否有一个特定的原因,这种优化会被遗漏。 Also the VC++ compiler definitely does seem to make this optimization, so I wonder why the discrepancy. VC ++编译器肯定似乎做了这个优化,所以我想知道为什么会出现这种差异。 Any ideas? 有任何想法吗?

No, none of the .NET jitters I know eliminate empty for loops. 不,我所知道的.NET抖动都没有消除for循环。 The exact reason why isn't that clear to me, the jitter optimizer certainly knows how to make optimizations like that and readily eliminates dead code. 确切的原因对我来说并不清楚,抖动优化器肯定知道如何进行这样的优化并且很容易消除死代码。 Check this answer for details. 请查看此答案以获取详细信 I believe this was intentional, leaving the loop in place for its possibly intended side-effect, consuming time. 我认为这是故意的,因为它可能有用的副作用留下了循环,耗费时间。 Which of course only makes sense for very short loops to implement a spinwait. 当然,这对于实现spinwait的非常短的循环来说是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM