views:

516

answers:

3

I'm trying to come up with a method which will measure and return the execution time of another method. Basically something like this:

public void DoSomething(Int32 aNumber)
{ /* Stuff happens */ }

//
// Somewhere else in code:
TimeSpan executionTime = MyDiag.MeasureExecTime(DoSomething(5));

// Now executionTime contains how long DoSomething(5) took to execute,
// e.g. 2.55463 seconds.

How can I do this (the MeasureExecTime method)?

+5  A: 

I've just created such a method to test performance in this SO question:

private static TimeSpan MeasureExecTime(Action action, int iterations)
{
    action(); // warm up
    var sw = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        action();
    }
    return sw.Elapsed;
}

Usage:

MeasureExecTime(() => DoSomething(5), 100000);

See 280Z28's answer if you don't want to test more than one iteration :-)

dtb
That was my question too. I actually got the idea to write this from your answer (w/ performance tests) in the other question. lol.
Alex
Your for loop adds overhead and may distort the results (although not significantly...). You should start the stopwatch before action(), and pause it after
Thomas Levesque
@Thomas, it has a few flaws, but calling action before stopwatch startnew is not one of them. See my answer.
Sam Saffron
+3  A: 
public static TimeSpan MeasureExecTime(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    return stopwatch.Elapsed;
}
280Z28
Just as good :) +1
Alex
+1  A: 

See this thread for a long discussion on this topic, the accepted answers has quite a few flaws.

Benchmarking small code samples in C#, can this implementation be improved?

Sam Saffron
Mine (not the accepted answer) isn't trying to be an accurate average measurement. For measuring exactly one call, it's just fine. :)
280Z28