我需要找到一个瓶颈,并需要尽可能准确地测量时间。

下面的代码片段是衡量性能的最佳方法吗?

DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);

当前回答

@Sean钱伯斯

供您参考,.NET Timer类不是用于诊断的,它以预设的时间间隔生成事件,如下(来自MSDN):

System.Timers.Timer aTimer;
public static void Main()
{
    // Create a timer with a ten second interval.
    aTimer = new System.Timers.Timer(10000);

    // Hook up the Elapsed event for the timer.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

    // Set the Interval to 2 seconds (2000 milliseconds).
    aTimer.Interval = 2000;
    aTimer.Enabled = true;

    Console.WriteLine("Press the Enter key to exit the program.");
    Console.ReadLine();
}

// Specify what you want to happen when the Elapsed event is 
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}

所以这并不能帮助你知道某件事花了多长时间,只是告诉你某段时间已经过去了。

计时器也作为一个控件在System.Windows.Forms…你可以在VS05/VS08的设计器工具箱中找到它

其他回答

Visual Studio Team System有一些功能可以帮助解决这个问题。从本质上讲,您可以编写单元测试,并将它们混合在不同的场景中,作为压力或负载测试的一部分对您的软件运行。这可能有助于识别对应用程序性能影响最大的代码区域。

微软的模式和实践小组在Visual Studio团队系统性能测试指南中提供了一些指导。

这篇文章说,首先你需要比较三个替代品,秒表,日期时间。Now AND DateTime.UtcNow。

它还显示在某些情况下(当性能计数器不存在时)Stopwatch正在使用DateTime。UtcNow +一些额外的处理。因此,在这种情况下,DateTime很明显。UtcNow是最好的选择(因为其他使用它+一些处理)

然而,事实证明,计数器几乎总是存在的-参见关于高分辨率性能计数器及其与. net秒表相关的存在的解释?

这是一个性能图表。请注意UtcNow的性能成本与其他选项相比有多低:

X轴是样本数据的大小,Y轴是样本的相对时间。

秒表更好的一点是它能提供更高分辨率的时间测量。另一个原因是它更加面向对象。然而,围绕UtcNow创建一个OO包装器并不难。

因为我不太关心精度,所以我最终比较了它们。我正在捕获网络上的大量数据包,我想在我收到每个数据包时放置时间。下面是测试500万次迭代的代码

    int iterations = 5000000;

    // Test using datetime.now
    {
        var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);

        var now = DateTime.UtcNow;

        for (int i = 0; i < iterations; i++)
        {
            if (date == DateTime.Now)
                Console.WriteLine("it is!");
        }
        Console.WriteLine($"Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
    }

    // Test using datetime.utcnow
    {
        var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);

        var now = DateTime.UtcNow;

        for (int i = 0; i < iterations; i++)
        {
            if (date == DateTime.UtcNow)
                Console.WriteLine("it is!");
        }
        Console.WriteLine($"Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
    }

    // Test using stopwatch
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        var now = DateTime.UtcNow;

        for (int i = 0; i < iterations; i++)
        {
            if (sw.ElapsedTicks == DateTime.Now.Ticks)
                Console.WriteLine("it is!");
        }
        Console.WriteLine($"Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
    }

输出结果为:

Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds 
Done executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds 
Done executing 5000000 iterations using stopwatch. It took 0.9625021 seconds

总之,DateTime。如果您不太关心精度,UtcNow是最快的。这也支持了这个问题的答案https://stackoverflow.com/a/6986472/637142。

我在程序中使用的方式是使用StopWatch类,如下所示。

Stopwatch sw = new Stopwatch();
sw.Start();


// Critical lines of code

long elapsedMs = sw.Elapsed.TotalMilliseconds;

如果你想要一些快速和肮脏的东西,我建议使用秒表代替更大程度的精度。

Stopwatch sw = new Stopwatch();
sw.Start();
// Do Work
sw.Stop();

Console.WriteLine("Elapsed time: {0}", sw.Elapsed.TotalMilliseconds);

或者,如果你需要一些更复杂的东西,你可能应该考虑使用第三方分析器,如ANTS。