When Time is of the Essence
I was reading this post today and, while I like the possibility to easily time specific parts of my code, I thought the solution given there was not accounting for a number of scenarios:
- What if we want to call a method that has parameters, or one that has a return value ?
- If an exception occurs in the method that's being timed, the timer breaks.
- The code being timed is limit to a single method. Ofcourse, we can always refactor our code in this direction, but still.
- Switching from a method call to passing method call as a delegate seems to change the semantics of the code. This might be a personal thing though.
I've used a similar solution in a number of my projects, which is based on a ctor/dispose-construct. Using it is as simple as placing a 'using'-construct around the code that you want to time:
using (new PerformanceTimer("Running MySlowMethod and MyOtherSlowMethod with parameters"))
{
MySlowMethod(X);
MyOtherSlowMethod(Y);
}
Running this will result in output being printed to the Log console telling us how long it took to execute the code. The code for the PerformanceTimer class is relatively simple:
public class PerformanceTimer : IDisposable
{
private DateTime _start;
private string _caption;
public PerformanceTimer(string caption)
{
_caption = caption;
_start = DateTime.Now;
}
public void Dispose() {
Log.Info("{0}: {1}ms.", _caption, Passed.TotalMilliseconds);
}
public TimeSpan Passed { get { return DateTime.Now - _start; } }
}
What I'm currently interested in is a way of storing these timing results in a database without influencing the performance of the application itself. That way I am able to easily collect live performance data over longer periods of time.
Posted by Filip at 15:05. 5 comments.