精确的时间测量性能测试精确、测量、性能测试、时间

2023-09-02 11:49:20 作者:醉梦人生

什么是看多长时间的东西,例如一个方法调用的最准确的方式,参加了code?

What is the most exact way of seeing how long something, for example a method call, took in code?

最简单快捷的我猜是这样的:

The easiest and quickest I would guess is this:

DateTime start = DateTime.Now;
{
    // Do some work
}
TimeSpan timeItTook = DateTime.Now - start;

但是,如何准确呢?有没有更好的办法呢?

But how exact is this? Are there better ways?

推荐答案

一个更好的办法是使用秒表类:

A better way is to use the Stopwatch class:

using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();

sw.Start();

// ...

sw.Stop();

Console.WriteLine("Elapsed={0}",sw.Elapsed);