Skip to content

Instantly share code, notes, and snippets.

@j2jensen
Created November 10, 2010 00:22
Show Gist options
  • Save j2jensen/670108 to your computer and use it in GitHub Desktop.
Save j2jensen/670108 to your computer and use it in GitHub Desktop.
Fill in the blanks to test the difference in performance between different actions.
void Main()
{
var actions = new[]
{
new TimedAction("first", () =>
{
// Insert logic here.
}),
new TimedAction("second", () =>
{
// Insert logic here.
})
};
TimeActions(1000000, actions);
}
#region timer helper methods
// Define other methods and classes here
public void TimeActions(int iterations, params TimedAction[] actions)
{
Stopwatch s = new Stopwatch();
foreach(var action in actions)
{
var milliseconds = s.Time(action.Action, iterations);
Console.WriteLine("{0}: {1}ms ", action.Message, milliseconds);
}
}
public class TimedAction
{
public TimedAction(string message, Action action)
{
Message = message;
Action = action;
}
public string Message {get;private set;}
public Action Action {get;private set;}
}
public static class StopwatchExtensions
{
public static double Time(this Stopwatch sw, Action action, int iterations)
{
sw.Restart();
for (int i = 0; i < iterations; i++)
{
action();
}
sw.Stop();
return sw.Elapsed.TotalMilliseconds;
}
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment