Sunday, 17 April 2016

Timing

 Though there are plenty of profilers on the market, most of them are huge and quite expensive software. Sometime the only thing needed is timing so you could understand where bottlenecks are. For that matter I started to use very simple piece of code:


public class SimpleTimeScope:IDisposable
 {
  private Stopwatch _stopwatch;
  private string _operation;

  public SimpleTimeScope(string operationName)
  {
   _operation = operationName;
   _stopwatch = new Stopwatch();
   _stopwatch.Start();
  }
  public void Dispose()
  {
   _stopwatch.Stop();
   TimeScopeResultProcessor.Instance.Register(_operation, _stopwatch.Elapsed);

  }
 }
Using this is  easy, here is the sample:



using (new SimpleTimeScope("MoveDoneToHistory"))
{
  _manager.MoveDoneToHistory();
}

TimeScopeResultProcessor.Instance.Register can be anything - usually writing to log (NLog, log4Net...) or even direct write to Console or database.  There is a room for improvement: using some interface in Dispose, ability to cope with nested operations (that's the thing I' working on right now).

No comments:

Post a Comment