问题
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?
回答1:
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();
}
}
回答2:
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.
回答3:
I would use a Timer
回答4:
A StopWatch
will have better precision.
来源:https://stackoverflow.com/questions/7388736/fastest-way-to-calculate-time-differences-in-c