Fastest way to calculate time differences in C#?

谁说我不能喝 提交于 2020-01-06 19:42:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!