Developing on Staxmanade

Timing Debug Code Using Lambda's

In applications that require responsiveness it's sometimes hard, while in the middle of development to test what implementation of some code is faster.

Below I've created an example of an easy way to time some action or group of actions within a method to quickly determine how long it would take to do it one way or another.



public void SomeMethodIAmWorkingOn()
{
TimeAction(
() =>
{
for (int i = 0; i < 100; i++)
SomeMethodIAmTiming();
SomeNextStep();
},
"Timing method SomeMethodIAmTiming 100 times...");
}

public static long TimeAction(
System.Action action,
string
debugNote)
{
long time = TimeAction(action);

System.Diagnostics.Debug.WriteLine(
string.Format(
"TimeAction:{0}ms, NOTE: {1},",
time,
debugNote)
);

return time;
}

public static long TimeAction(
System.Action action)
{
Stopwatch watch = Stopwatch.StartNew();
action();
watch.Stop();
return watch.ElapsedMilliseconds;
}

Comments

Jason.Jarrett
whoops - Thanks for the suggested update...
Anonymous
Lambda, not lamda. ;)

Comments