有没有一种方法来获得净JIT或C#编译器优化掉空的for循环? [英] Is there a way to get the .Net JIT or C# compiler to optimize away empty for-loops?

查看:266
本文介绍了有没有一种方法来获得净JIT或C#编译器优化掉空的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个后续到是否.NET JIT优化空循环走?

下面的程序只运行一个空循环十亿倍,并打印出运行的时间。它需要700毫秒我的机器上,我很好奇,如果有一种方式来获得抖动优化掉的空循环。

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.

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);
        }
    }
}

据我可以告诉答案是否定的,但我不知道是否有隐藏的编译器选项我可能没有尝试过。我已经确定编制在释放模式和不附加任何调试器中运行,但是仍然700毫秒正在采取运行该空循环。我也试过NGEN具有相同的结果(虽然我的理解是,它应该产生相同的编译code作为JIT呢,对吧?)。不过,我从来没有使用NGEN前,可能会使用它错了。

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. 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?). However I've never used NGEN before and may be using it wrong.

它的似乎的像这样的会是容易的JIT查找和优化掉,但是了解甚少抖动一般是如何工作的,我很好奇,如果有一个具体的原因,这个优化将遭到冷落。另外,VC ++编译器肯定似乎使这种优化,所以我不知道为什么的差异。任何想法?

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. Also the VC++ compiler definitely does seem to make this optimization, so I wonder why the discrepancy. Any ideas?

推荐答案

没有,没有一个.NET紧张,我知道的消除空循环。确切的原因不是很清楚,我,抖动优化肯定知道如何让这样的优化和易于消除死code。检查<一href="http://stackoverflow.com/questions/4043821/performance-differences-between-debug-and-release-builds/4045073#4045073">this回答了解详细信息。我相信这是故意的,离开循环到位的可能预期的副作用,耗时。这当然只能是有道理的,很短的循环来实现spinwait。

No, none of the .NET jitters I know eliminate empty for loops. 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.

这篇关于有没有一种方法来获得净JIT或C#编译器优化掉空的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆