Find out how long your method runs
I am making some experiments with large database and different O/R-mappers. To make it easier for me to measure the time that code takes to run I wrote simple command class that uses Stopwatch class and measures how long it takes for action to run. I this posting I will show you my class and explain how to use it.
Here is the code of my class. You can take it and put it to some temporary project to play with it.
/// <summary>
/// Class for executing code and measuring the time it
/// takes to run.
/// </summary>
public class TimerDelegateCommand
{
private readonly Stopwatch _stopper = new Stopwatch();
/// <summary>
/// Runs given actions and measures time. Inherited classes
/// may override this method.
/// </summary>
/// <param name="action">Action to run.</param>
public virtual void Run(Action action)
{
_stopper.Reset();
_stopper.Start();
try
{
action.Invoke();
}
finally
{
_stopper.Stop();
}
}
/// <summary>
/// Static version of action runner. Can be used for "one-line"
/// measurings.
/// </summary>
/// <param name="action">Action to run.</param>
/// <returns>Returns time that action took to run in
/// milliseconds.</returns>
public static long RunAction(Action action)
{
var instance = new TimerDelegateCommand();
instance.Run(action);
return instance.Time;
}
/// <summary>
/// Gets the action running time in milliseconds.
/// </summary>
public long Time
{
get { return _stopper.ElapsedMilliseconds; }
}
/// <summary>
/// Gets the stopwatch instance used by this class.
/// </summary>
public Stopwatch Stopper
{
get { return _stopper; }
}
}
And here are some examples how to use it. Notice that I don’t have to write methods for every code piece I want to measure. I can also use anonymous delegates if I want. And one note more – Time property returns time in milliseconds!
static void Main()
{
long time = TimerDelegateCommand.RunAction(MyMethod);
Console.WriteLine("Time: " + time);
time = TimerDelegateCommand.RunAction(delegate
{
// write your code here
});
Console.WriteLine("Time: " + time);
Console.WriteLine("\r\nPress any key to exit ...");
Console.ReadLine();
}
You can also extend this command and write your own logic that drives code running and measuring. In my next posting I will show you how to apply Command pattern to make some more powerful measuring of processes.