A small piece of code; if you want to test the speed of a function, you can use a timer. I created a helper function to capture this stopwatch timer. It executes your code and shows the amount of time it took to execute the action. Feedback is welcome.
/// <summary>
/// Measures the time it took to execute a function.
/// <example>
/// Call this function like this:
/// <code>MeasureTime("test", () => { // code });</code>
/// </example>
/// </summary>
/// <param name="message">The message to show after the test.</param>
/// <param name="action">The action to execute.</param>
public void MeasureTime(string message, Action action)
{
MeasureTime(message, 1, action);
}
/// <summary>
/// Measures the time it took to execute a function.
/// <example>
/// Call this function like this:
/// <code>MeasureTime("test", 4, () => { // code });</code>
/// </example>
/// </summary>
/// <param name="message">The message to show after the test.</param>
/// <param name="times">The times to run it.</param>
/// <param name="action">The action to execute.</param>
public void MeasureTime(string message, int times, Action action)
{
var sw = new Stopwatch();
for (int i = 0; i < times; i++)
{
sw.Start();
action();
sw.Stop();
}
var s = times == 1 ?
string.Format("{0}: {1}", message, sw.Elapsed) :
string.Format("{0}: #{1}; total {2}, avg {3}", message, times, sw.Elapsed, TimeSpan.FromTicks(sw.ElapsedTicks / times));
Console.WriteLine(s);
Debug.WriteLine(s);
}
To use, call the function using an Action.
MeasureTime("Only once", () => { string s = "a" + "b" + "c" + "d"; });
MeasureTime("More times", 1000000, () => { string s = "a" + "b" + "c" + "d"; });
MeasureTime("More times with String.Concat", 1000000, () => string.Concat( "a" , "b", "c", "d"));
The result will be displayed to the console and the debug window:
Only once: 00:00:00.0000603
More times: #1000000; total 00:00:01.4219715, avg 00:00:00.0000003
More times with String.Concat: #1000000; total 00:00:01.5199820, avg 00:00:00.0000003