Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Tip/Trick

How To: Measure execution time in C#

Rate me:
Please Sign up or sign in to vote.
4.83/5 (29 votes)
1 Mar 2011CPOL1 min read 138.9K   37   8
How To Measure execution time in C#
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.

C#
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.
C#
double frequency = Stopwatch.Frequency;
double nanosecPerTick = (1000 * 1000 * 1000) / frequency;
// return the value in nanosec
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Marwin Cassovia Soft
Slovakia Slovakia
My name is Robert Kanasz and I have been working with ASP.NET, WinForms and C# for several years.
MCSD - Web Applications
MCSE - Data Platform
MCPD - ASP.NET Developer 3.5
- Web Developer 4
MCITP - Database Administrator 2008
- Database Developer 2008
MCSA - SQL Server 2012
MCTS - .NET Framework 3.5, ASP.NET Applications
- SQL Server 2008, Database Development
- SQL Server 2008, Implementation and Maintenance
- .NET Framework 4, Data Access
- .NET Framework 4, Service Communication Applications
- .NET Framework 4, Web Applications
MS - Programming in HTML5 with JavaScript and CSS3 Specialist

Open source projects: DBScripter - Library for scripting SQL Server database objects


Please, do not forget vote

Comments and Discussions

 
GeneralReason for my vote of 5 I could have used this a few days ag... Pin
lewax007-Oct-11 10:51
lewax007-Oct-11 10:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.