-3

I want to measure the time that certain function calls take in my application. For this I use the Stopwatch class and it works fine. It looks something like this:

static readonly Stopwatch StopWatch = new Stopwatch();

StopWatch.Restart();
void func();
StopWatch.Stop();
Assert.Blabla

However I am typing this around a lot of functions. Is there a way to make a function that does this for me? I tried but since the signatures of the functions are all different I can't figure it out. I took a look at Func and Action, but they seem to require a fixed signature. I would like something like this:

CallAndMeasureFunction(func)
Frank
  • 2,446
  • 7
  • 33
  • 67
  • Yes, C# is a strongly typed language, of course you need a fixed signature.... – Milney Jul 05 '17 at 08:46
  • 4
    This is called profiling. Use a .NET profiling tool to gve you these statistics. See the answer here https://stackoverflow.com/questions/14019510/calculate-the-execution-time-of-a-method (series0ne answer) –  Jul 05 '17 at 08:47
  • Or look into a library like: https://github.com/petabridge/NBench – Milney Jul 05 '17 at 08:47
  • How about you make a function like what you suggested: CallAndMeasureFunction(){Stopwatch.Start(), func1(); check stopwatch time, func2(), check stopwatch time, func3()...Stopwatch.Stop()}, so you can check time taken by all functions in your application just by calling this function. Will this not suffice? – Arvind Sasikumar Jul 05 '17 at 08:47

1 Answers1

1

You can use something like below:

Define a method which takes your actual methods delegate as input:

public static TimeSpan GetTimestampFor(Action action)
    {
        TimeSpan timestamp = new TimeSpan(0);
        Stopwatch stopWatch = new Stopwatch();

        if (action != null)
        {
            stopWatch.Start();
            action.Invoke();
            stopWatch.Stop();

            timestamp = stopWatch.Elapsed;
        }

        return timestamp;
    }

and call it as below:

var timeSpan = GetTimestampFor(() => {var xyz = ActualMethodForWhichTimeHasTobeMeasured()});

With this code, you can measure every method's execution time

Sujith
  • 1,604
  • 9
  • 16
  • Unfortunately I cannot use Action because the return value is not always void. – Frank Jul 05 '17 at 09:17
  • 1
    Updated the code above. This code can be used to any kind of method whether you have a return type or not. If you don't have a return type just remove the {var xyz = and } – Sujith Jul 05 '17 at 09:21