Console.WriteLine加快我的代码?

我一直在研究如何加速我的应用程序,因为它对性能至关重要……即每一毫秒我都可以摆脱它更好。 为此,我有一个调用其他方法的方法,其中每个方法都包含一个Stopwatch计时器和Console.WriteLine调用。 即:

 private void SomeMainMethod() { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); SomeMethod(); sw.Stop(); Console.WriteLine("Time for SomeMethod = {0}ms", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); SomeOtherMethod(); sw.Stop(); Console.WriteLine("Time for SomeOtherMethod= {0}ms", sw.ElapsedMilliseconds); //... } 

问题是每当我注释掉StopwatchConsole.WriteLine行代码运行大约20ms(而不是50)慢,这是我需要的很多。

有人知道为什么吗?

编辑: SomeMainMethod方法和类中的其他方法也包含在类似于上面的StopwatchConsole.WriteLine调用中。

SomeMainMethod及其调用的方法是类的一部分,该类是从控制台测试平台调用的类库的一部分,所有这些都是单线程的。

有关更多信息:该应用程序在x86 .NET 4.6.1发布模式下运行,并启用了优化。 我也在视觉工作室2013中运行它,而不是在它之外。

在阅读了一个没有答案的非常相似的问题后 ,我可能已经找到了问题。 在评论部分,用户(ForguesR)发表了以下评论:

这真是一个很大的猜测:也许是因为你写的IO你的线程获得更多的处理器时间,因为WriteLine是同步的,因此阻止其他线程。

所以我想检查是否确实如此,所以我将SomeMainMethod更改为以下内容:

注意 :通常不建议使用线程优先级,这只是测试理论的一种解决方法。 我强烈建议不要在生产代码中这样做,除非你100%确定你知道自己在做什么。 然后可能仍然远离它。

 private void SomeMainMethod() { System.Threading.ThreadPriority tp = System.Threading.ThreadPriority.Normal; try { tp = System.Threading.Thread.CurrentThread.Priority; System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); SomeMethod(); sw.Stop(); Console.WriteLine("Time for SomeMethod = {0}ms", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); SomeOtherMethod(); sw.Stop(); Console.WriteLine("Time for SomeOtherMethod= {0}ms", sw.ElapsedMilliseconds); //... } finally { System.Threading.Thread.CurrentThread.Priority = tp; } } 

进行此更改后,当ConsoleStopwatch线被注释掉时,我的代码现在可以更快地运行(~10ms)。 所以我相信他的评论可能是正确的,至少在我的情况下。