如何在c#中使用秒表计算执行实际时间?

时间:2014-04-23 15:19:38

标签: c# asp.net-mvc

我在方法中尝试了以下代码:

Trace.Write("START "+Datetime.now);
//DATABASE METHOD CALL 
SaveData();
Trace.Write("END "+Datetime.now);

我手动计算output window的时间。

如何使用stopwatch(启动/重置/停止)来获取正确的执行时间?

3 个答案:

答案 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;

StopWatch