Measuring method execution time I want to easily measure method's execution time. Of course instead of doing something like this:

var timer = Stopwatch.StartNew();
DoSomething();
timer.Stop();
Console.WriteLine(timer.ElapsedMilliseconds)


I want to make it more elegant. What I've managed is something like this:

static class MethodMeasurer
{
    public static T Invoke&lt;T&gt;(Func&lt;T&gt; action, out Stopwatch stopwatch)
    {
        var timer = Stopwatch.StartNew();
        var res = action.Invoke();
        timer.Stop();
        stopwatch = timer;
        return res;
    }

    public static void Invoke(Action action, out Stopwatch stopwatch)
    {
        var timer = Stopwatch.StartNew();
        action.Invoke();
        timer.Stop();
        stopwatch = timer;
    }
}


And here is the usage:

class Program
{
    static void Main(string[] args)
    {
        MethodMeasurer.Invoke(DoSomething1, out var s1);
        Console.WriteLine("s1 executed time: " + s1.ElapsedMilliseconds);

        var doSomething2Measured = MethodMeasurer.Invoke(DoSomething2, out var s2);
        Console.WriteLine("s2 executed time: " + s2.ElapsedMilliseconds);
        Console.WriteLine("s2 returned: " + doSomething2Measured);

        var doSomething3Measured = MethodMeasurer.Invoke(() =&gt; DoSomething3(5), out var s3);
        Console.WriteLine("s3 executed time: " + s3.ElapsedMilliseconds);
        Console.WriteLine("s3 returned: " + doSomething3Measured);
    }

    static void DoSomething1()
    {
        Thread.Sleep(100);
    }

    static int DoSomething2()
    {
        Thread.Sleep(300);
        return 1;
    }

    static int DoSomething3(int i)
    {
        Thread.Sleep(300);
        return i;
    }
}


So what do you think about that? Would you suggest I use a different solution, or is mine okay?
Because you are interested in the time it took and not the stopwatch, you should return a TimeSpan. And since we no longer need stopwatch as a parameter, we can rename timer to stopwatch (as "timer" makes me think of the Timer class).

public static void Invoke(Action action, out TimeSpan timeSpan)
{
    var stopwatch = Stopwatch.StartNew();
    action.Invoke();
    stopwatch.Stop();
    timeSpan = stopwatch.Elapsed;
}