Using the StopWatch class to calculate the execution time of a block of code
- by vik20000in
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