Using the StopWatch class to calculate the execution time of a block of code

Posted by vik20000in on ASP.net Weblogs See other posts from ASP.net Weblogs or by vik20000in
Published on Wed, 21 Apr 2010 01:28:00 GMT Indexed on 2010/04/21 1:33 UTC
Read the original article Hit count: 555

Filed under:
|
|
|
|

 

Many of the times while doing the performance tuning of some, class, webpage, component, control etc. we first measure the current time taken in the execution of that code. This helps in understanding the location in code which is actually causing the performance issue and also help in measuring the amount of improvement by making the changes.

This measurement is very important as it helps us understand the problem in code, Helps us to write better code next time (as we have already learnt what kind of improvement can be made with different code) .

Normally developers create 2 objects of the DateTime class. The exact time is collected before and after the code where the performance needs to be measured.  Next the difference between the two objects is used to know about the time spent in the code that is measured.

Below is an example of the sample code.

            DateTime dt1, dt2;

            dt1 = DateTime.Now;

            for (int i = 0; i < 1000000; i++)

            {

                string str = "string";

            }

            dt2 = DateTime.Now;

            TimeSpan ts = dt2.Subtract(dt1);

            Console.WriteLine("Time Spent : " + ts.TotalMilliseconds.ToString());

 

The above code works great. But the dot net framework also provides for another way to capture the time spent on the code without doing much effort (creating 2 datetime object, timespan object etc..). We can use the inbuilt StopWatch class to get the exact time spent. Below is an example of the same work with the help of the StopWatch class.

            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < 1000000; i++)

            {

                string str = "string";

            }

            sw.Stop();

            Console.WriteLine("Time Spent : " +sw.Elapsed.TotalMilliseconds.ToString());

 

[Note the StopWatch class resides in the System.Diagnostics namespace]

If you use the StopWatch class the time taken for measuring the performance is much better, with very little effort.

Vikram

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET