Mar 4, 2010

Calculating Elapsed Time Accurately (C#)

To calculate elapsed time in our code, we normally do ,

DateTime stTime = DateTime.Now;
.....
// Do some work here
....
DateTime etTime = DateTime.Now;
TimeSpan ts = etTime – stTime;
But, this method won’t always give accurate value. I found Stopwatch class in System.Diagnostics namespace to calculate accurate elapsed time. Should look into it.

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine(elapsedTime, "RunTime");
    }
}

Above example directly taken from MSDN. For more information check this link, http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

5 comments:

Julian M. said...

Awesome! I am using this snippet to check the time elapsed to convert a PowerPoint presentation on http://slideonline.com - Definitely this is more accurate than the DateTime approach. Thanks for the share.

In my case, the output was: total time elapsed 00:01:32.46

Anonymous said...

Just found this post. The StopWatch is SO much more accurate than timespan!

I'm actually using the built in function .ElapsedMilliseconds to display how long my queries are taking.

Sara said...

This is great! It helped me a lot. But, I have a huge problem and I hope You can help me.

In my task, I have two fields that user define: first one represents number of seconds since 1/1/1997, and second contains the number of microseconds within that second. Do you know how can I calculate date based on user's data?

Greetings!

Kelum Ganegoda said...

Hi Sara,

Did you try out with
DateTime(long ticks)

use following links..

http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

http://msdn.microsoft.com/en-us/library/z2xf7zzk.aspx

Hope this will help you.

Thanks.
Regards.

Anonymous said...

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

// do stuff

stopWatch.Stop();
long duration = stopWatch.ElapsedMilliseconds;

MEC: How to Set Message Counter for EDI Message

When you sending/creating EDI messages it is necessary to include unique message interchange number. This is to ensure each message that we ...