Measure the code execution time using Stopwatch instance in C#

In this article, learn how to measure the code execution time using Stopwatch instance in C#. In C#, the System.Diagnostics namespace of System.Runtime.dll has the Stopwatch class which can be used to accurately measure the time taken for code execution.


How to measure the code execution time using Stopwatch instance in C#?

You can use a Stopwatch instance to measure elapsed time for one interval or the total of elapsed time across multiple intervals. In the below example, you can see how to use the Stopwatch scenario where the Start method is called first, then eventually the Stop method is called, and then Elapsed property is checked for the time taken to execute the piece of code.

The following example demonstrates how to use the Stopwatch class to determine the execution time for an application of a for loop.

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main()
        {
            Stopwatch sp = new Stopwatch();

            //Start the stopwatch
            sp.Start();

            for (int i = 0; i < 5000; i++)
            {
                //Do something.
            }

            //Stop the stopwatch. 
            sp.Stop();

            //Read the total execution time into the TimeSpan object.
            TimeSpan ts = sp.Elapsed;

            //Read the total execution time measured in miliseconds.
            long lElpTimeMs = sp.ElapsedMilliseconds;

            //Read the total execution time measured in timer ticks
            long lElpTicks = sp.ElapsedTicks;

            //Reset the stopwatch that will clear/reset the timer information to 0. 
            if (sp.IsRunning)
            {
                sp.Reset();
            }

            //Or - Restart the stopwatch which does the stopwatch Reset() and stopwatch Start() internally
            sp.Restart();

            //Print measured time
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                ts.Hours, 
                                                ts.Minutes, 
                                                ts.Seconds,
                                                ts.Milliseconds / 10);
            Console.WriteLine("Total Elapsed Time: " + elapsedTime);
            Console.WriteLine("Total Elalsed time in Miliseconds", lElpTimeMs.ToString());
            Console.WriteLine("Total Elalsed time in Timer Ticks", lElpTicks.ToString());
        }
    }
}



- Article ends here -

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Informix Database Connection String in C#
Share this:

Tags:

We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo