2

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)?

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Alex
  • 75,813
  • 86
  • 255
  • 348
  • 1
    Duplicate of http://stackoverflow.com/questions/232848/wrapping-stopwatch-timing-with-a-delegate-or-lambda ? – Matt Hamilton Aug 27 '09 at 23:29
  • How is this a duplicate to Jeff's question on measuring via lambda? And besides, I already accepted an answer to this question, too much time on your hands? – Alex Aug 27 '09 at 23:34
  • 2
    The fact that the accepted answer is almost identical to the accepted answer on the other question makes me wonder if it's a duplicate, that's all. No need to be snarky about it. – Matt Hamilton Aug 27 '09 at 23:56
  • 1
    Might I ask why? If you're wanting to do some quick benchmarks, great; if you want to profile an application, use a profiler. There's a bare-bones free one at http://www.eqatec.com/tools/profiler and there are several full-featured commercial offerings (ANTS, dotTrace). – TrueWill Aug 28 '09 at 00:05

2 Answers2

7

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 :-)

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 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 Aug 27 '09 at 22:53
  • 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 Aug 27 '09 at 22:57
  • 2
    @Thomas, it has a few flaws, but calling action before stopwatch startnew is not one of them. See my answer. – Sam Saffron Aug 27 '09 at 23:03
7
public static TimeSpan MeasureExecTime(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    return stopwatch.Elapsed;
}
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280