定时器比间隔多花 10 毫秒 [英] Timer takes 10 ms more than interval

查看:22
本文介绍了定时器比间隔多花 10 毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用间隔为 1 秒的计时器.但是在计时器的滴答事件中,当我打印时间时,它总是 62 或 65 毫秒.我不明白为什么要多花 10 毫秒.

I am using a timer with interval 1 second. But in the timer's tick event when I print the time it's always 62 or 65 ms. I don't understand why it's taking 10 ms more.

请有人研究一下.

这是我使用的代码:

static int _counter;
var _timer = new System.Timers.Timer(1000);
public Form1()
{
    InitializeComponent();           
    _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
    _timer.Start();            
}

private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Console.WriteLine(DateTime.Now.ToString("{hh:mm:ss.fff}"));          
    _counter++;
    if (_counter == 20)
        _timer.Stop();
}

这是输出:

{01:59:08.381}
{01:59:09.393}
{01:59:10.407}
{01:59:11.421}
{01:59:12.435}
{01:59:13.449}
{01:59:14.463}
{01:59:15.477}
{01:59:16.491}
{01:59:17.505}
{01:59:18.519}
{01:59:19.533}
{01:59:20.547}
{01:59:21.561}
{01:59:22.575}
{01:59:23.589}
{01:59:24.603}
{01:59:25.615}
{01:59:26.629}
{01:59:27.643}

推荐答案

您需要了解 Windows 不是实时操作系统.实时操作系统具有定时器机制,允许系统对定时器启动的事件何时发生以及与它们相关的开销做出硬保证,并允许您指定在错过最后期限时应该发生的行为——例如,如果之前的执行时间比间隔时间长.

You need to understand that Windows is not a real-time operating system. Real-time operating systems have timer mechanisms that allow the system to make hard guarantees about when timer-initiated events occur and the overhead associated with them, and allow you to specify what behavior should occur when the deadline is missed -- for example if the previous execution took longer than the interval.

当涉及到较小的间隔时,我会将 Windows 计时器描述为尽力而为".当间隔足够长时,您不会注意到您没有得到您请求的确切间隔.当您越来越接近计时器的分辨率(计时器运行的频率)时,您开始看到开销与时间间隔的百分比增加.实时系统特别注意最大限度地减少软件开销,依赖于更复杂和更快的硬件解决方案.Windows 计时器的确切频率取决于底层硬件提供的计时服务,因此可能因系统而异.

I would characterize the Windows timers as "best effort" when it comes to smaller intervals. When the interval is sufficiently long you don't notice that you aren't getting the exact interval that you requested. As you get closer and closer to the resolution of the timer (the frequency at which the timer runs), you start seeing the overhead as a percentage of the interval increase. Real-time systems take special care to minimize the software overhead, relying on more sophisticated and faster hardware solutions. The exact frequency of the Windows timer depends on the timing services that the underlying hardware provides and so may differ from system to system.

如果您有实时需求——并且每 50 毫秒做某事可能属于该类别——那么您可能需要查看专门的硬件和/或实时操作系统.

If you have real-time needs -- and doing something every 50ms may fall into that category -- then you may need to look at specialized hardware and/or a real-time OS.

这篇关于定时器比间隔多花 10 毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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