如何制作一个精确的十进制计时器? [英] How to make an accurate decimal Timer?

查看:117
本文介绍了如何制作一个精确的十进制计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此我感到非常沮丧。

我有一个称为 timer1 的计时器框 TimeElapsedTextBox double 变量 TimeTakenToFinish
计时器在文本框中每1秒(1000毫秒)
计时一次,我希望它以这种格式显示时间:

I have a timer called timer1 and a text box called TimeElapsedTextBox and a double variable called TimeTakenToFinish the timer ticks every 1 second (1000 millisecond) in the text box, I want it to display the time in this format:

Seconds.PartsOfSecond

以下是滴答事件:

private void timer1_Tick(object sender, EventArgs e)
{
  TimeTakenToFinish += (double)timer1.Interval / 10000;
  TimeElapsedTextBox.Text = TimeTakenToFinish;
}

实际上是按照我想要的方式在文本框中显示它,
,但计数不正确..
我的意思是,它的计数还不到真正的秒。.

it is actually displaying it in the text box the way i want it, but it's not counting properly .. I mean, it's counting less than a real second..

请告诉我如何解决此问题..

could you please tell me how to fix this ..

推荐答案

您的问题是对操作系统工作方式的误解。当然,您可以将间隔设置为 1000ms ,但是您不能期望它实际上每秒都在计时。您正在Windows而不是硬(或软)实时操作系统上运行代码。

Your problem here is a misunderstanding of the way your OS works. Sure, you can set the interval to 1000ms, but you cannot expect it to actually tick every second. You are running code on Windows, not a hard (or soft) real time operating system.

顺便说一句,您还应该知道计时器的分辨率是有限的,并且从今天起,它仅限于系统计时器的精度,这大概与15ms。

As an aside, you should also know that the resolution of your timer is finite, and as of today, limited to the accuracy of your system timer, which is probably about 15ms.

您不能期望您的代码在那种环境下能够确定地执行。在任何时候,操作系统都可以抢先将您踢出CPU并开始执行其他任务。

You cannot expect your code to perform that deterministically in that sort of environment. At any point the OS can preemptively kick you out of the CPU and start working on another task.

尽管我会问,但是您根本无法获得所需的准确性;实际需要吗?可能不是,但是您没有告诉我们您实际上想在这里完成什么,所以谁知道呢?

You simply cannot get the accuracy you desire, though I would ask; is it actually required? Probably not, but you haven't told us what you are actually trying to accomplish here, so who knows?

此外,这是错误的:

TimeTakenToFinish += (double)timer1.Interval / 10000;

时间间隔是用于大致告诉计时器应该多久触发一次 Tick 事件。您实际上并没有测量任何东西,您最好每次都将 1000.0 / 10000 添加到您的计数器。

Interval is a property which is used to tell the timer roughly how often it should fire the Tick event. You are not actually measuring anything, you may as well just be adding 1000.0 / 10000 to your counter every time.

如果需要更高的精度,请使用 StopWatch 类,该类使用CPU的高性能计时器(如果有)。您仍然可以使用计时器根据秒表的当前经过的值定期更新UI,即

If you need more precision use the StopWatch class which uses your CPU's high performance timer if available. You can still use a timer to periodically update the UI based on the current elapsed value of the Stopwatch, i.e.,

void timer1_Tick(...)
{
    var totalSeconds = _someStopwatch.ElapsedMilliseconds / 1000.0;
    TimeElapsedTextBox.Text = totalSeconds.ToString();
}

这篇关于如何制作一个精确的十进制计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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