Have an operation to measure? Use Stopwatch()


Quite often we run into situations where we need to measure the elapsed time of a method/operation, and there are number of ways to do it. The simplest way to do is by using a Stopwatch. This class is available under the namespace System.Diagnostics.

To show you a demo, I have used a simple app which calculates the time taken to load a website on your local machine.

namespace Nish.Stopwatch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("WebAddress> ");
            Console.WriteLine("Your website took about " + LoadWebsite(Console.ReadLine()).Seconds + " seconds to load on your machine");
            Console.ReadLine();
        }

        /// <summary>
        /// Gets the load time of a website
        /// </summary>
        /// <param name="websitePath">Path in the format: e.g. http://nnish.com </param>
        /// <returns>Time taken</returns>
        private static TimeSpan LoadWebsite(string websitePath)
        {
            System.Diagnostics.Stopwatch stpWatch = new System.Diagnostics.Stopwatch();
            stpWatch.Start();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(websitePath);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Read the data in the stream
            StreamReader streamReader = new StreamReader(response.GetResponseStream());
            // s – will have your html content, I am not using this for now
            string s = streamReader.ReadToEnd();
            stpWatch.Stop();
            
            return stpWatch.Elapsed;
        }
    }
}

 

Time took for my website to load:

image

Look at the time Google took:

image

And now this was out of curiosity:

image

Please note: The load time depends on various factors like network speed, server location,  page content etc. So this data should not be treated as accurate. The idea of having this example is to show the usage of Stopwatch and not to determine the speed of the website.

Method Stopwatch.Start() starts the timer, and ticks in parallel until the Stopwatch.Stop() is executed. The start method does not start the elapsed time at 0, if executed again. To set the elapsed time to 0 use either Stopwatch.Restart() or call Stopwatch.Reset() before the next start(). So understand that “A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset/restarted.” – MSDN. To start a fresh timer use Stopwatch stopwatch = Stopwatch.StartNew() which is a static method.

This comes very handy when you use this for all your performance monitoring or benchmarking on/the your operations.

Cheers!

Advertisements

2 thoughts on “Have an operation to measure? Use Stopwatch()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s