怎样才能最准确地看到某个东西(例如一个方法调用)在代码中花费了多长时间?

我猜最简单和最快的方法是:

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

但这有多精确呢?有没有更好的办法?


当前回答

秒表是好的,但循环工作10^6次,然后除以10^6。 你会得到更精确的结果。

其他回答

使用Stopwatch类

更好的方法是使用Stopwatch类:

using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();

sw.Start();

// ...

sw.Stop();

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

秒表是好的,但循环工作10^6次,然后除以10^6。 你会得到更精确的结果。

我用这个:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
System.Diagnostics.Stopwatch timer = new Stopwatch();

timer.Start();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

statusCode = response.StatusCode.ToString();

response.Close();

timer.Stop();

stopwatch就是为这个任务设计的。