Reputation: 10284
It seems like there are a lot of ways to calculate time spans in c#. I am wondering which one is fastest and by that I simply means requires the least amount of processing. Let me throw out an example to illustrate exactly what I am trying to do.
private const int timeBetweenEvents = 250; //delay ms
DateTime nextUpdate = DateTime.Now.Add(new TimeSpan(0, 0, 0, timeBetweenEvents));
...
while(true)
{
if (DateTime.Now > nextUpdate)
{
// do something
nextUpdate = DateTime.Now.Add(new TimeSpan(0, 0, 0, timeBetweenEvents));
}
// ...
// do some other stuff
// ...
}
another option...
private const int timeBetweenEvents = 250; //delay ms
TimeSpan nextUpdate = DateTime.Now.TimeOfDay.Add(new TimeSpan(0,0,0,timeBetweenEvents));
...
while(true)
{
if (DateTime.Now.TimeOfDay > nextUpdate)
{
// do something
nextUpdate = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 0, 0, timeBetweenEvents));
}
// ...
// do some other stuff
// ...
}
I have also seen similar things by doing subtractions using System.Environment.TickCount. So what is the bst way to do this?
Upvotes: 0
Views: 3173
Reputation: 14331
If you're looking for performance, at the very least cache the value of DateTime.Now
outside of the loop. I remember reading it can be a relatively expensive function to call.
Upvotes: 2
Reputation: 9218
DateTime
, Environment.TickCount
and Thread.Sleep
have a resolution of 30ms - which may cause problems. Stopwatch
doesn't have this problem (on platforms that support it, i.e. pretty much any machine today) - plus the code is also a little shorter (the fastest code is code that is never executed) and clearer.
const long millisecondsBetweenEvents = 250;
var sw = new Stopwatch();
sw.Start();
while(true)
{
if (sw.ElapsedMilliseconds > millisecondsBetweenEvents)
{
// do something
sw.Restart();
}
}
Upvotes: 2