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.
{
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:
Look at the time Google took:
And now this was out of curiosity:
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!
Nish,Intresting …Good to know….keep updating your blog
Thanks Nalina :)