Sometimes developers need to measure execution time of task. This method could be useful when is important to compare two or more approaches and choose the best. .NET Framework contains
Stopwatch
class that can measure elapsed time for one interval, or total elapsed time across multiple intervals.
For more information, navigate to:
Stopwatch Class.
The following example demonstrates how to use
Stopwatch
class to determine execution time for an application. Using this example, you can see differences in efficiency by calling
Contains
method of
StringCollection
and
HashTable
.
Hashtable hs = new Hashtable();
StringCollection sc = new StringCollection();
for (int i = 0; i < int.MaxValue/1000; i++)
{
hs.Add(i.ToString(), i);
sc.Add(i.ToString());
}
Random rnd = new Random();
Stopwatch timer = new Stopwatch();
int val = rnd.Next(int.MaxValue / 1000);
timer.Start();
if (sc.Contains(val.ToString()))
{
Console.WriteLine("Contains");
}
timer.Stop();
Console.WriteLine(timer.ElapsedTicks);
timer.Reset();
timer.Start();
if (hs.Contains(val.ToString()))
{
Console.WriteLine("Contains");
}
timer.Stop();
Console.WriteLine(timer.ElapsedTicks);
Added by Alex Bell:
This solution by
Kanasz Robert is very efficient and adhere to the .NET paradigm of managed code (no "unsafe" code). The similar solution was implemented in the test site dedicated to the Toggle Case Algorithm performance comparison (e.g., see the Ayoola-Bell Algorithm at:
http://webinfocentral.com/resources/toggleCaseAlgorithm.aspx[
^].
That particular solution in addition to the code block similar to this one, contains the following code snippets, intended to calculate the elapsed time of the algorithm under the test in nanoseconds (might me microseconds, etc.) rather than in ticks, thus extending the capabilities and presenting the result in user-friendly format (ns, us, etc.):
Listing 1.
double frequency = Stopwatch.Frequency;
double nanosecPerTick = (1000 * 1000 * 1000) / frequency;
double durNanosec = timer.ElapsedTicks * nanosecPerTick;
As the general rule, when testing the extremely fast algorithms (like the Ayoola-Bell Toggle Case, mentioned above with completion time in the range of several microseconds) it's recommended to implement the loop running 10,000...100,000 iterations in order to increase the accuracy of the measurement. Also, be aware of the useful property
Stopwatch.IsHighResolution
(boolean), which indicates the Stopwatch capability pertinent to the particular HW/OS settings.