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();
        // 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,


Julian said...

Awesome! I am using this snippet to check the time elapsed to convert a PowerPoint presentation on - 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?


Kelum Ganegoda said...

Hi Sara,

Did you try out with
DateTime(long ticks)

use following links..

Hope this will help you.


Anonymous said...

Stopwatch stopWatch = new Stopwatch();

// do stuff

long duration = stopWatch.ElapsedMilliseconds;