Wednesday, January 6, 2010

Measuring execution time in C#

How to measure a method's execution time without using timer?

Use DateTime and TimeSpan classes in .net framework.

public void sampleMethod()
{
DateTime starttime = DateTime.Now;
//
//......
//do code here
//......
DateTime endtime = DateTime.Now;
TimeSpan duration = endtime - starttime;
string time = duration.Hours + ":" + duration.Minutes + ":" + duration.Seconds + ":" + duration.Milliseconds;
}

No comments: