Wednesday 2 February 2011

Csharp: measuring execution time of code blocks

Question:
How to mesure execution time of a method in csharp?
Measuring any time interval in dot.Net.



Answer:
Measuring a time interval or the execution time of a process is not very relyable.
There are several ways to do this. For example:
DateTime.UtcNow - Or - Process.TotalProcessorTime - Or - Stopwatch.StartNew

This is a good comparison of advantages and drawbacks: Beware of Stopwatch

Here is an example using StopWatch
static TimeSpan ProfileExecTime(Action func, int iterations)
{
    // clean up your memory
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    func(); // warm up
    var sw = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        func();
    }
    return sw.Elapsed;
}
...

No comments: