Use Stopwatch instead of DataTime for getting accurate performance counter. (Viewed - 3193 times)



In C# (Visual Studio .NET), the DateTime class is not recommended for high precision timing. To have high precision timing calculation in your application use Stopwatch class. It can be accessed through System.Diagnostics.Stopwatch (Means the class is under System.Diagnostics namespaces).

Note: DateTime class is not recommended if you need accuracy:

 
using System;

class Program
{
    public static void Main()
    {
        DateTime start = DateTime.Now;

            // some other code

        DateTime stop = DateTime.Now;

        // Bad way of calculating accurate timing
        Console.WriteLine("{0} ms", (stop - start).TotalMilliseconds);

        // Bad way of calculating accurate timing
        Console.WriteLine("{0} ms", (stop - start).Milliseconds);
    }
}


Stopwatch uses operating system high-resolution performance counter
 
using System;
using System.Diagnostics;

class Program
{
    public static void Main()
    {
        Stopwatch stopWatch = Stopwatch.StartNew();

            // some other code

        stopWatch.Stop();

        // this not correct to get full timer resolution
        Console.WriteLine("{0} ms", stopWatch.ElapsedMilliseconds);

        // Correct way to get accurate high precision timing
        Console.WriteLine("{0} ms", stopWatch.Elapsed.TotalMilliseconds);
    }
}


As i already explained that Stopwatch class is in the System.Diagnostics namespace, therefore you have to add following using statement on top
 
using System.Diagnostics;


As i mentioned that Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer (DateTime class) to measure elapsed time.

Not question comes to your mind that how you check your system supports a high-resolution performance counter?

Use check the Stopwatch.IsHighResolution property

 
if (Stopwatch.IsHighResolution)
{
    Console.WriteLine("Using the system's high-resolution performance counter.");
}
else
{
    Console.WriteLine("Using the DateTime class.");
}


How to check the timing accuracy?
Well you can use the Stopwatch.Frequency property

 long frequency = Stopwatch.Frequency;



Post Article  Post Code 
  Post Tip    Start Forum
 
Quick note for developers
Google+
Follow