Please navigate to the bottom of the page for Table of Contents

Sunday, July 29, 2012

How to time any function

One key aspect during performance testing is to time how long a function takes to execute. In this small post, I will show how to create a generic timing function that takes as argument the function to time and shows the time to execute along with the output of the function:

/// <summary>
/// Times the execution of a function and outputs both the elapsed time and the function's result.
/// </summary>
static void Time<T>(Func<T> work)
    var sw = Stopwatch.StartNew();
    var result = work();
    Console.WriteLine(sw.Elapsed + ": " + result);

To call the time, use the following invocation style:

Time(() => DoSomeWork());

No comments:

Post a Comment