我在方法中尝试了以下代码:
Trace.Write("START "+Datetime.now);
//DATABASE METHOD CALL
SaveData();
Trace.Write("END "+Datetime.now);
我手动计算output window
的时间。
如何使用stopwatch
(启动/重置/停止)来获取正确的执行时间?
答案 0 :(得分:6)
按Stopwatch创建Stopwatch.StartNew
的实例,执行您的方法。停止Stopwatch
然后获取ElapsedMilliseconds
,如:
Stopwatch stopwatch = Stopwatch.StartNew();
SaveData();
stopwatch.Stop();
Trace.Write("Time in Millisecond: " + stopwatch.ElapsedMilliseconds);
请记住加入using System.Diagnostics;
答案 1 :(得分:2)
使用Stopwatch类:
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Do something
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1);
}
// Stop timing
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed: {0}",
stopwatch.Elapsed);
答案 2 :(得分:2)
根据msdn:
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;