Tuesday, September 21, 2010

How to measure the time the method takes to run in C#

.Net framework provides StopWatch class in (System.Diagnostics.StopWatch). we can use this class to measure the time for a method takes to finish executing.


private delegate void AnyFunc();

private TimeSpan MeasureMe(AnyFunc f)
{
    System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
    stopWatch.Start();
    f.Invoke();
    stopWatch.Stop();
    TimeSpan ts = stopWatch.Elapsed;
    return ts;
}

Cheers!

1 comments:

lauren said...

StopWatch class is really a boon to those developer who are very much thoughtful about efficient execution of the program rather then writing just a working code.To improve total speed we may check methods speed separately and will come to know which method need to be optimized in terms of speed
digital signature

Post a Comment