Using the Stopwatch Timer

There are times when it is useful to measure how long a piece of code takes to execute. This can be achieved with the Stopwatch class. The Stopwatch is in the System.Diagnostics namespace.

Here is a simple example of how to use the class:

Stopwatch sw = new Stopwatch();
sw.Start(); 

// do some code here 

sw.Stop();
Console.WriteLine("Elapsed Time: {0}",sw.ElapsedMilliseconds); 

If you do not replace the comment with some real code the elapsed time will probably be 0.

It is also possible to restart the time like you would with a normal stop watch. In the example blow there is a sleep command to create a delay in the execution. The thread class is in the System.Threading namespace.

var sw2 = Stopwatch.StartNew(); 
for (var i = 0; i <= 10000; i++)
{
    Thread.Sleep(1);
}
Console.WriteLine("Elapsed Time:",sw2.ElapsedMilliseconds);
sw2.Restart(); 

for (var i = 0; i <= 10000; i++)
{
    Thread.Sleep(1);
}
sw2.Stop();
Console.WriteLine("Elapsed Time:", sw2.ElapsedMilliseconds); 

The above example also shows how to initialise the stopwatch and create a new instance of the class on a single line using the static StartNew method.