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

4
  • 1
    Duplicate of stackoverflow.com/questions/232848/… ? Commented Aug 27, 2009 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? Commented Aug 27, 2009 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. Commented Aug 27, 2009 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 eqatec.com/tools/profiler and there are several full-featured commercial offerings (ANTS, dotTrace). Commented Aug 28, 2009 at 0:05

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

That was my question too. I actually got the idea to write this from your answer (w/ performance tests) in the other question. lol.
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, it has a few flaws, but calling action before stopwatch startnew is not one of them. See my answer.
7
public static TimeSpan MeasureExecTime(Action action) { Stopwatch stopwatch = Stopwatch.StartNew(); action(); return stopwatch.Elapsed; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.