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.
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.