测量两个任务的时间

时间:2014-01-29 04:43:08

标签: c# .net time timespan stopwatch

我的程序中有两个任务,我需要计算每个任务的时间,我读到stopwatchTimeSpan,但我不知道我必须使用哪个,怎么做,我想要以毫秒为单位测量每项任务的时间

for (int num = 2; num < 243; num++)
   {
     do something\\ compute time for first task
     do something\\ compute time for second task

    }

2 个答案:

答案 0 :(得分:3)

您可以轻松地将Stopwatch用于此

 Stopwatch watch = new Stopwatch();

  watch.Start();

  // do something
  watch.Stop();

  Console.WriteLine(watch.ElapsedMilliseconds);
  watch.Reset();

  watch.Start();
  // do something different
  ...

答案 1 :(得分:0)

var start = DateTime.Now;
//code to measure
var timeTaken = (DateTime.Now - start).TotalMilliseconds;