0

Possible Duplicate:
Environment.TickCount vs DateTime.Now

In my application I require fast timing operations but accuracy is not that important. I checked the runtime speed of the three timing operations for which I am familiar with and came up with these results:

for (int i = 0; i < 1000000; i++) 
{
    // var time = (DateTime.Now - dt).TotalMilliseconds; // 1131 ms
    // var time = (Environment.TickCount - dt); // 7 ms
    // var time = stopwatch.ElapsedMilliseconds; // 131 ms
}

The times were checked using a Stopwatch. So, I want to use Environment.TickCount (I think!) but its problem is that after 24.9 days if the user is very unlucky the operation of 2,147,483,647 - -2,147,483,648 will occur and result in an overflow error and crash the program.

So, my question is two-fold. Firstly, is Environment.TickCount the best tool for the job given my specified goals, and secondly, whether anyone else has written a wrapper class for it and if so, how did you take in to account the rare overflow chance?

Community
  • 1
  • 1
Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • @AlexeiLevenkov: Yes I saw that thread but most replies were suggesting the use of `Stopwatch` and none of the replies spoke of proposed fixes to the overflow issue. – Ryan Peschel Feb 28 '12 at 18:07
  • You really want to use `DateTime.Now.Ticks` as it is a long, so no overflow (at least, not for a *very* long time). That said, the above is the question you are asking, you wouldn't use `Environment.TickCount`, but `DateTime.Ticks`. – casperOne Feb 28 '12 at 18:13
  • @RyanPeschel, BTW, you've seen Matthew comment on rollover in the question - overflow takes care of rollover automatically. – Alexei Levenkov Feb 28 '12 at 18:14

1 Answers1

0

While I think it is duplicate of discussion on TickCount vs. Now...

Is TickCount the best tool you need to decide yourself. If 100ms matters for 1 million of operations you plan to measure - probably, but I strongly doubt as precision of TickCount is 10ms your average error for that many measurements would be about 5ms*10^6.

I think you should create wrapper class for your time measurement, but mainly not to protect from wraparound, but to allow unit testing of your code. It is not easy to mock system-wide time functions, but custom class can be setup for ease of use and testing.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179