在 C# 中计算时差的最快方法? [英] Fastest way to calculate time differences in C#?

查看:80
本文介绍了在 C# 中计算时差的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 c# 中似乎有很多方法可以计算时间跨度.我想知道哪个最快,我只是说需要最少的处理.让我举一个例子来说明我想要做什么.

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
   // ...
}

另一种选择...

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
   // ...
}

通过使用 System.Environment.TickCount 进行减法,我也看到过类似的事情.那么这样做的最佳方法是什么?

I have also seen similar things by doing subtractions using System.Environment.TickCount. So what is the bst way to do this?

推荐答案

我会使用 计时器

这篇关于在 C# 中计算时差的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆