Using System.Diagnostics.Stopwatch class to measure the elapsed time

I’ve been playing around with the Stopwatch class using .NET Framework 4.0. It contains great set of methods which you can use to measure the elapsed time while your code executes.

It's definitely better to use Stopwatch instead of DateTime or TimeSpan in order to measure the elapsed time.

Here is one example.

Lets create a test where we will make one million iterations and some simple calculation.

Using the Stopwatch class and it’s Start() and Stop() methods, we will measure the elapsed time

Stopwatch stopWatch = new Stopwatch(); //creating object of Stopwatch class
stopWatch.Start(); //starting the stopwatch
/*************************/            
int sum = 0;            
for (int i = 0; i < 1000000; i++)
{
    sum = sum + i;          
}
/*************************/
stopWatch.Stop(); //stop the stopWatch
Response.Write("Sum is:" + sum + "<br /> Calculation of the time elapsed:"+stopWatch.Elapsed);

 

The output result is

Sum is:1783293664
Calculation of the time elapsed:00:00:00.0029783

 

So, the elapsed time to iterate over one million elements using FOR loop and calculate ‘sum = sum + i’ is 00:00:00.0029783 (about 3 milliseconds).

You can get the result in milliseconds or in time ticks too:

stopWatch.ElapsedTicks – in ticks
stopWatch.ElapsedMilliseconds – in milliseconds (will round it – in our example the result will be 3)

Moreover, there are other useful methods inside the Stopwatch class, such as:

stopWatch.Reset() – will reset the time to zero
stopWatch.Restart() – will reset the elapsed time to zero and start the stopwatch automatically (restart)

You can also use stopWatch.IsRunning boolean property to check whether the Stopwatch is running or not.

You can read more about this class on the MSDN article.

I’ve also written an article FOR vs FOREACH – performance tests and analysis in CodeASP.NET Community (you need to be registered to read the article).

I hope this was useful info for you.

Regards,
Hajan

3 Comments

Comments have been disabled for this content.