Console.WriteLine加速了我的代码?

The*_*der 6 c# console performance

我一直在研究如何加速我的应用程序,因为它对性能至关重要......即每一毫秒我可以摆脱它更好.为此,我有一个调用其他方法的方法,其中每个方法都包含一个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);

    //...
}
Run Code Online (Sandbox Code Playgroud)

问题是,每当我注释掉StopwatchConsole.WriteLine行代码运行约20毫秒(不是50)慢是很多关于我需要什么.

有人知道为什么吗?

编辑:SomeMainMethod方法和其他人在类也包裹在一个StopwatchConsole.WriteLine调用类似于上面.

SomeMainMethod和它调用是一个类,它是一个类库是从一个控制台测试平台,所有这些都是单线程称为部分的一部分方法.

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

The*_*der 2

在阅读了一个非常相似但没有答案的问题后,我可能发现了这个问题。在评论部分,一位用户(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

进行此更改后,当ConsoleStopwatch行被注释掉时,我的代码现在运行速度始终更快(约 10 毫秒)。因此我相信他的评论可能是正确的,至少在我的情况下是这样。