Skip to main content

C# helper method to output the total run time of an Action.

using System;
using System.Threading.Tasks;

class Program
{
    public static void RunTimeIt()
    {
        Thread.Sleep(1000);
    }

    static void Main(string[] args)
    {
        TimeIt(RunTimeIt); // => 'RunTimeIt' took '00:00:01.0033254'.
    }

    public static void TimeIt(Action action)
    {
        Stopwatch timer = Stopwatch.StartNew();
        action();
        timer.Stop();
        Console.WriteLine("'{0}' took '{1}'.", action.Method.Name, timer.Elapsed);
    }
}