Make a way to return the execution time of another method

I am trying to come up with a method that 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 (MeasureExecTime method)?

+2


source to share


4 answers


I just created a method like this 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;
}

      

Using:



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

      

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

+7


source


public static TimeSpan MeasureExecTime(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    return stopwatch.Elapsed;
}

      



+7


source


See this thread for a long discussion of this thread, the accepted answers have quite a few drawbacks.

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

+1


source


0


source







All Articles