Friday, February 18, 2011

Measure execution time in C#

Sometimes developers need to measure execution time of task. This methodics 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.

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);

No comments:

Post a Comment