C# Stopwatch – How to Measure Time Elapsed Accurately in C#

If you are into code performance optimisation then you would have probably heard about the C# stopwatch class. It’s an awesome class that C# provides out of the box to programmers, by which they can measure the execution time of a piece of code. Stopwatch class is contained inside the ‘System. Diagnostics’ namespace and was introduced with .Net 2.0.

The beauty of C# Stopwatch class is that it allows you to calculate elapsed time over a number of intervals with the total elapsed time measured by adding all of the intervals together. In a typical scenario you could initiate a stopwatch, by calling the Start method, then later you would call the Stop method and finally use the Elapsed property to get the total time elapsed. But, this class is capable of more.

C# Stopwatch Class

How MSDN Defines C# Stopwatch Class:

Stopwatch class “Provides a set of methods and properties that you can use to accurately measure elapsed time”.

Code Snippet Example of using .Net Stopwatch Class:

Below is an example of how to use Stopwatch class in .Net:

using System;
using System.Diagnostics;
using System.Threading;

namespace Stopwatch_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of StopWatch
            Stopwatch watch = new Stopwatch();

            //Start the StopWatch
            watch.Start();

            //Perform Some Action
            for (int i = 0; i < 1000; i++)
            {
                Thread.Sleep(1);
            }

            //Stop the StopWatch
            watch.Stop();

            //Check Elapsed Time
            Console.WriteLine("Time elapsed as per stopwatch: {0} ",
            watch.Elapsed);

            Console.ReadKey();
        }
    }
}
Output:
Time elapsed as per stopwatch: 00:00:06.1780356

Explaining the above code snippet:

Line 12: On line 12 we have used the statement ‘Stopwatch watch = new Stopwatch()’ – this statement creates a new instance of the stopwatch class.

Line 15: On line 15 we have used the ‘Start’ Method on the instance of the Stopwatch class – this method internally calls the QueryPerformanceCounter (which is a WIN 32 API) to get the current Tick count of the system. The Tick count that we get here is extremely accurate.

Line 24: On line 24 we have used the ‘Stop’ Method on the instance of the Stopwatch class – this method again tells the stopwatch instance to capture the system Tick count accurately.

Line 27: On line 27, inside Console.WriteLine() we have used the ‘Elapsed’ property on the instance of the Stopwatch class – this property is a TimeSpan struct that gives you the total time elapsed between the Start and Stop methods.

Note: Please note that in the above code, inside the loop using the ‘Thread.Sleep’ Method is optional, you can simply ignore this if you do not know what it does.

Few Important Points about Stopwatch Class:

Below are few important points about the C# Stopwatch class:

  1. Using C# Stopwatch class can be good to identify performance gaps, but using Stopwatch itself causes a performance overhead. So, it is not a good practice to leave it in your production code.
  2. The Stopwatch calculates elapsed time by counting timer ticks in the underlying timer mechanism. If the hardware and operating system support a high-resolution performance counter, then the C# Stopwatch class uses that counter to compute elapsed time by using QueryPerformanceCounter() WinAPI function. Otherwise, the Stopwatch class uses the system timer (DateTime.Ticks) to determine elapsed time.
  3. Stopwatch class has higher resolution and precision than using two ‘DateTime.Now’ variables and subtracting them to find the elapsed time.

Other Members of Stopwatch Class:

In addition to the above explained methods and properties, Stopwatch class also has following important members:

StartNew Method:

This method can simplify your code, by allowing you to create a new stopwatch and initiating the stopwatch instance in a single command. This uses a creational design pattern to return a new instance (which is started) from a static type method.

Below is the code snippet to explain this:

class Program
    {
        static void Main(string[] args)
        {
            //Create a Stopwatch instance and start it
            var watch = Stopwatch.StartNew();

            //Perform Some Action
            for (int i = 0; i < 1000; i++)
            {
                System.Threading.Thread.Sleep(1);
            }

            //Stop the StopWath
            watch.Stop();

            //Check Elapsed Time
            Console.WriteLine("Time elapsed as per stopwatch: {0}",
            watch.Elapsed);

            Console.ReadKey();
        }
   }

So, in this code segment you can clearly see that instead of writing two statements – One for creating a Stopwatch instance and other for initializing it we are just using the StartNew Method.

Reset and Restart Method:

The Stopwatch instance contains Restart and Reset methods. Restart sets the timer information to zero. After this it calls Start method again on the Stopwatch, so that you are ready for measuring elapsed time again.

On the other hand, Reset Method only sets the timer information to zero. It does not call the Start Method on the Stopwatch. So, using Restart method is equivalent to call Reset and Start methods one after another.

Below is an example of Restart Method:

class Program
    {
        static void Main(string[] args)
        {
            //Create a Stopwatch instance and start it
            var watch = Stopwatch.StartNew();

            //Waiting for 2 second
            Thread.Sleep(2000);

            //Restarting the stopwatch
            watch.Restart();

            //Waiting for 2 second
            Thread.Sleep(2000);
            //Stop the StopWath
            watch.Stop();

            //Check Elapsed Time
            Console.WriteLine("Time elapsed as per stopwatch:  {0}",
            watch.Elapsed);

            Console.ReadKey();
        }
    }
Output:
Time elapsed as per stopwatch: 00:00:02.0024055

ElapsedMilliseconds and ElapsedTicks Property:

ElapsedMilliseconds property gives you the elapsed time in milliseconds. The value of milliseconds is rounded down to the nearest whole millisecond value. For higher precision calculations, use the Elapsed or ElapsedTicks properties.

ElapsedTicks property gives the total elapsed time measured by the current instance, in timer ticks. This is internally a readonly signed System.Int64 value. Tick is smallest unit of elapsed time a stopwatch timer can measure. If you are using ElapsedTicks property of stopwatch class then you may need to convert the resultant Ticks to seconds.

Note: It should be noted that Stopwatch ticks are not equal to DateTime.Ticks. Because a single tick in the DateTime. DateTime.Tick represents one 100th nanosecond interval. Whereas each tick in the ElapsedTicks value represents the time interval equal to 1 second divided by the Frequency.

Code Snippet for Calculating Elapsed Seconds using ElapsedTicks:

class Program
    {
        static void Main(string[] args)
        {
            //Create a Stopwatch instance and start it
            var watch = Stopwatch.StartNew();

            //Perform Some Action
            for (int i = 0; i < 1000; i++)
            {
                Thread.Sleep(1);
            }

            //Stop the StopWath
            watch.Stop();

            //Check Elapsed Time
            Console.WriteLine("Time elapsed as per stopwatch: {0} sec!",
            (watch.ElapsedTicks / Stopwatch.Frequency));

            Console.ReadKey();
        }
    }

Output:
Time elapsed as per stopwatch: 9 sec!

Frequency and IsHighResolution Property:

In the above example we have seen the Stopwatch frequency. Frequency and IsHighResolution are implemented as static properties in the C# stopwatch class. Frequency indicates the number of ticks per second. It is used for converting ElapsedTicks to seconds.

IsHighResolution tells whether the stopwatch is running on a high-resolution performance counter or not. If this is false that means the Stopwatch is not running on a high-resolution performance counter and hence its accuracy is low.

If the hardware and OS support a high-resolution performance counter (determined by IsHighResolution), then the C# Stopwatch class uses that counter to compute elapsed time by using QueryPerformanceCounter() WinAPI function (which is very accurate). Otherwise, the Stopwatch class uses the system timer (DateTime.Ticks) to determine elapsed time (which is not so much accurate).

IsRunning Property:

IsRunning is also a static property of Stopwatch class, which returns a Boolean value specifying whether the stopwatch is started or not. In most cases, you won’t find it useful but in case your code uses Stop or Reset Methods in unpredictable ways then you may want to use this property.

So, this was all about Stopwatch class in C#. Do let us know in case you have any queries or would like to share any other info related to the topic.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>