Sunday, April 8, 2007

Timer class

I was checking the difference in performance between SqlDataReader and DataTableReader. I needed something to measure time with. I wrote a simple class Timer. It worked just fine for me; however, I find it hard to believe that .Net framework doesn’t have anything to measure time. The reason for this post is that I hope that someone can suggest a better solution to my Timer class.
Here’s there Timer class:

public class Timer
  long _start;
  long _stop;

  public void Start()
    _start = GetTimeInMilliseconds();

  public void Stop()
    _stop = GetTimeInMilliseconds();

  public long TimeElapsed
    get { return _stop - _start; }

  private long GetTimeInMilliseconds()
    return DateTime.Now.Hour * 60 * 60 * 1000
      + DateTime.Now.Minute * 60 * 1000
      + DateTime.Now.Second * 1000
      + DateTime.Now.Millisecond;

In case you’re interested in performance difference between SqlDataReader and DataTableReader. Here’re my findings:
On single CPU machine SqlDataReader was faster and it of course was expected. However, on double CPU machine DataTableReader was slightly faster and this was a pleasant surprise for me.


Chuck said...

If you're using .Net 2.0, you can use the Stopwatch class:

Vadim said...

chuck, thanks a lot. It definitely would work. If I new about Stopwatch class, I would use it instead of writing my own timer.