Click here to Skip to main content
15,885,985 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

How To: Measure execution time in C#

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
9 Mar 2011CPOL 9.5K   1   1
Please try this method to get execution time. I'm not sure that it is very accurate.public static TimeSpan GetDuration(Stopwatch sw, ThreadStart method){ sw.Reset(); sw.Start(); method(); sw.Stop(); return sw.Elapsed;}you can put it into any common static class and use as...
Please try this method to get execution time. I'm not sure that it is very accurate.

public static TimeSpan GetDuration(Stopwatch sw, ThreadStart method)
{
	sw.Reset();
	sw.Start();
	method();
	sw.Stop();
	return sw.Elapsed;
}


you can put it into any common static class and use as follows:

IList dataObjects = GetObjects(); // execution time should be tested

foreach (DataObject do in dataObject)
{
}


Execution time can be measured in such way:

IList dataObjects = null;
Stopwatch sw = new Stopwatch();
Console.WriteLine("GetObjects executed in {0}", GetDuration(sw, delegate() {

dataObjects = GetObjects();

}));
foreach (DataObject do in dataObject)

License

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


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionYou can get more precise measurements! Pin
Pavel Vladov11-Jul-12 22:12
Pavel Vladov11-Jul-12 22:12 
Unfortunately executing the test only once may not give you accurate time measurement as there's a lot of activity going on under the hood of the OS, which can steal CPU time and slow down you code. That's why it is best to execute the tests and measure the times multiple times and then remove the lowest and the highest times.

For more information take a look at the following article: Measure C# Code Performance

modified 5-Sep-12 4:10am.

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.