txdv / LibuvSharp

.NET bindings for libuv
176 stars 41 forks source link

Don't use DateTime.Now for timing #10

Closed mattjohnsonpint closed 9 years ago

mattjohnsonpint commented 9 years ago

All throughout the examples and tests, there is code like this:

var now = DateTime.Now;
// ... do something ...
span = DateTime.Now - now;

You should never use DateTime.Now for timing operations.

  1. The computer's RTC is not all that precise.
  2. The user can easily adjust the clock at any time.
  3. The OS will adjust the clock periodically to sync with network time servers.
  4. Daylight saving time changes can create large shifts in local time.
  5. DateTime.Now calls DateTime.UtcNow under the hood anyway, and then applies the local time zone.

For timing operation, use a System.Diagnostics.Stopwatch.

You can do any of the following:

var stopwatch = Stopwatch.StartNew();
// .. do the thing ...
stopwatch.Stop();
TimeSpan span = stopwatch.Elapsed;
var stopwatch = new Stopwatch();
for (var foo in alotofthings)
{
    stopwatch.Restart();
    // .. do the things ...
    TimeSpan span = stopwatch.Elapsed;
}
long start = Stopwatch.GetTimestamp();
// .. do the thing(s) ...
long stop = Stopwatch.GetTimestamp();
long elapsed = stop - start;
TimeSpan elapsedTime = TimeSpan.FromSeconds(elapsed * (1.0 / Stopwatch.Frequency));
txdv commented 9 years ago

Old habits, thanks for reporting! I'll fix it asap.

txdv commented 9 years ago

Also if you are trying the latest master, it might break on windows because https://github.com/txdv/LibuvSharp/commit/e6cb6f94640ef294716500ed9f26002b4d71fa03 this fix is I think mono specific, just a head ups.

txdv commented 9 years ago

Although these are just examples and not really critical code, I appreciate your input and fixed everything according!

Thanks!

mattjohnsonpint commented 9 years ago

Looks good. Glad I could help. :)