为什么 .NET 计时器的分辨率限制为 15 毫秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3744032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are .NET timers limited to 15 ms resolution?
提问by Jim Mischel
Note that I'm asking about something that will call a callback function more often than once every 15 ms using something like System.Threading.Timer. I'm not asking about how to accurately time a piece of code using something like System.Diagnostics.Stopwatchor even QueryPerformanceCounter.
请注意,我问的是使用类似System.Threading.Timer. 我不是在问如何使用类似System.Diagnostics.Stopwatch或什至QueryPerformanceCounter.
Also, I've read the related questions:
另外,我已经阅读了相关问题:
Accurate Windows timer? System.Timers.Timer() is limited to 15 msec
准确的 Windows 计时器?System.Timers.Timer() 限制为 15 毫秒
Neither of which supplies a useful answer to my question.
两者都没有为我的问题提供有用的答案。
In addition, the recommended MSDN article, Implement a Continuously Updating, High-Resolution Time Provider for Windows, is about timing things rather than providing a continuous stream of ticks.
此外,推荐的 MSDN 文章为 Windows 实现持续更新的高分辨率时间提供程序是关于计时,而不是提供连续的滴答流。
With that said. . .
照这样说。. .
There's a whole lot of bad information out there about the .NET timer objects. For example, System.Timers.Timeris billed as "a high performance timer optimized for server applications." And System.Threading.Timeris somehow considered a second class citizen. The conventional wisdom is that System.Threading.Timeris a wrapper around Windows Timer Queue Timersand that System.Timers.Timeris something else entirely.
有很多关于 .NET 计时器对象的错误信息。例如,System.Timers.Timer被标榜为“为服务器应用程序优化的高性能计时器”。并且System.Threading.Timer以某种方式被认为是二等公民。传统观点认为它System.Threading.Timer是 Windows Timer Queue Timers的包装器,System.Timers.Timer而这完全是另一回事。
The reality is much different. System.Timers.Timeris just a thin component wrapper around System.Threading.Timer(just use Reflector or ILDASM to peek inside System.Timers.Timerand you'll see the reference to System.Threading.Timer), and has some code that will provide automatic thread synchronization so you don't have to do it.
实际情况大不相同。 System.Timers.Timer只是一个薄组件包装器System.Threading.Timer(只需使用 Reflector 或 ILDASM 来查看内部System.Timers.Timer,您就会看到对 的引用System.Threading.Timer),并且有一些代码可以提供自动线程同步,因此您不必这样做。
System.Threading.Timer, as it turns out is nota wrapper for the Timer Queue Timers. At least not in the 2.0 runtime, which was used from .NET 2.0 through .NET 3.5. A few minutes with the Shared Source CLI shows that the runtime implements its own timer queue that is similar to the Timer Queue Timers, but never actually calls the Win32 functions.
System.Threading.Timer,事实证明它不是定时器队列定时器的包装器。至少不是在 2.0 运行时中,它从 .NET 2.0 到 .NET 3.5 使用。几分钟的共享源 CLI 显示运行时实现了自己的计时器队列,类似于计时器队列计时器,但从未实际调用 Win32 函数。
It appears that the .NET 4.0 runtime also implements its own timer queue. My test program (see below) provides similar results under .NET 4.0 as it does under .NET 3.5. I've created my own managed wrapper for the Timer Queue Timers and proved that I can get 1 ms resolution (with quite good accuracy), so I consider it unlikely that I'm reading the CLI source wrong.
.NET 4.0 运行时似乎也实现了自己的计时器队列。我的测试程序(见下文)在 .NET 4.0 下提供了与在 .NET 3.5 下类似的结果。我已经为 Timer Queue Timers 创建了自己的托管包装器,并证明我可以获得 1 ms 的分辨率(具有相当好的准确性),所以我认为我不太可能读错 CLI 源代码。
I have two questions:
我有两个问题:
First, what causes the runtime's implementation of the timer queue to be so slow? I can't get better than 15 ms resolution, and accuracy seems to be in the range of -1 to +30 ms. That is, if I ask for 24 ms, I'll get ticks anywhere from 23 to 54 ms apart. I suppose I could spend some more time with the CLI source to track down the answer, but thought somebody here might know.
首先,是什么导致运行时对计时器队列的实现如此缓慢?我无法获得超过 15 毫秒的分辨率,精度似乎在 -1 到 +30 毫秒的范围内。也就是说,如果我要求 24 毫秒,我会得到间隔 23 到 54 毫秒的刻度。我想我可以花更多时间使用 CLI 源来追踪答案,但我想这里有人可能知道。
Second, and I realize that this is harder to answer, why not use the Timer Queue Timers? I realize that .NET 1.x had to run on Win9x, which didn't have those APIs, but they've existed since Windows 2000, which if I remember correctly was the minimum requirement for .NET 2.0. Is it because the CLI had to run on non-Windows boxes?
其次,我意识到这更难回答,为什么不使用 Timer Queue Timers?我意识到 .NET 1.x 必须在没有这些 API 的 Win9x 上运行,但它们自 Windows 2000 以来就存在,如果我没记错的话,这是 .NET 2.0 的最低要求。是因为 CLI 必须在非 Windows 机器上运行吗?
My timers test program:
我的计时器测试程序:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace TimerTest
{
class Program
{
const int TickFrequency = 5;
const int TestDuration = 15000; // 15 seconds
static void Main(string[] args)
{
// Create a list to hold the tick times
// The list is pre-allocated to prevent list resizing
// from slowing down the test.
List<double> tickTimes = new List<double>(2 * TestDuration / TickFrequency);
// Start a stopwatch so we can keep track of how long this takes.
Stopwatch Elapsed = Stopwatch.StartNew();
// Create a timer that saves the elapsed time at each tick
Timer ticker = new Timer((s) =>
{
tickTimes.Add(Elapsed.ElapsedMilliseconds);
}, null, 0, TickFrequency);
// Wait for the test to complete
Thread.Sleep(TestDuration);
// Destroy the timer and stop the stopwatch
ticker.Dispose();
Elapsed.Stop();
// Now let's analyze the results
Console.WriteLine("{0:N0} ticks in {1:N0} milliseconds", tickTimes.Count, Elapsed.ElapsedMilliseconds);
Console.WriteLine("Average tick frequency = {0:N2} ms", (double)Elapsed.ElapsedMilliseconds / tickTimes.Count);
// Compute min and max deviation from requested frequency
double minDiff = double.MaxValue;
double maxDiff = double.MinValue;
for (int i = 1; i < tickTimes.Count; ++i)
{
double diff = (tickTimes[i] - tickTimes[i - 1]) - TickFrequency;
minDiff = Math.Min(diff, minDiff);
maxDiff = Math.Max(diff, maxDiff);
}
Console.WriteLine("min diff = {0:N4} ms", minDiff);
Console.WriteLine("max diff = {0:N4} ms", maxDiff);
Console.WriteLine("Test complete. Press Enter.");
Console.ReadLine();
}
}
}
采纳答案by Arnold Spence
Perhaps the document linked here explains it a bit. It's kinda dry so I only browsed it quickly :)
也许这里链接的文件解释了一点。它有点干,所以我只快速浏览了它:)
Quoting the intro:
引用介绍:
The system timer resolution determines how frequently Windows performs two main actions:
- Update the timer tick count if a full tick has elapsed.
- Check whether a scheduled timer object has expired.
A timer tick is a notion of elapsed time that Windows uses to track the time of day and thread quantum times. By default, the clock interrupt and timer tick are the same, but Windows or an application can change the clock interrupt period.
The default timer resolution on Windows 7 is 15.6 milliseconds (ms). Some applications reduce this to 1?ms, which reduces the battery run time on mobile systems by as much as 25 percent.
系统计时器分辨率决定了 Windows 执行两个主要操作的频率:
- 如果一个完整的滴答已经过去,则更新计时器滴答计数。
- 检查计划的计时器对象是否已过期。
计时器滴答是 Windows 用来跟踪一天中的时间和线程量子时间的经过时间的概念。默认情况下,时钟中断和计时器滴答是相同的,但 Windows 或应用程序可以更改时钟中断周期。
Windows 7 上的默认计时器分辨率为 15.6 毫秒 (ms)。一些应用程序将这一时间减少到 1?ms,从而将移动系统上的电池运行时间减少多达 25%。
Originally from: Timers, Timer Resolution, and Development of Efficient Code (docx).
回答by Arno
The timer resolution is given by the system heartbeat. This typically defaults to 64 beats/s which is 15.625 ms. However there are ways to modify these system wide settings to achieve timer resolutions down to 1 ms or even to 0.5 ms on newer platforms:
定时器分辨率由系统心跳给出。这通常默认为 64 次/秒,即 15.625 毫秒。但是,有一些方法可以修改这些系统范围的设置,以在较新的平台上实现低至 1 ms 甚至 0.5 ms 的计时器分辨率:
1. Going for 1 ms resolution by means of the multimedia timer interface:
1. 通过多媒体定时器接口达到 1 ms 分辨率:
The multimedia timer interface is able to provide down to 1 ms resolution.
See About Multimedia Timers(MSDN), Obtaining and Setting Timer Resolution(MSDN), and thisanswer for more details about timeBeginPeriod. Note: Don't forget to call the timeEndPeriodto switch back to the default timer resolution when done.
多媒体定时器接口能够提供低至 1 毫秒的分辨率。请参见关于多媒体计时器(MSDN),获取和设置计时器分辨率(MSDN),并且这个答案如需详细了解timeBeginPeriod。注意:不要忘记在完成后调用timeEndPeriod以切换回默认的计时器分辨率。
How to do:
怎么做:
#define TARGET_RESOLUTION 1 // 1-millisecond target resolution
TIMECAPS tc;
UINT wTimerRes;
if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR)
{
// Error; application can't continue.
}
wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
timeBeginPeriod(wTimerRes);
// do your stuff here at approx. 1 ms timer resolution
timeEndPeriod(wTimerRes);
Note: This procedure is availble to other processes as well and the obtained resolution applies system wide. The highest resoltion requested by any process will be active, mind the consequences.
注意:此过程也可用于其他进程,并且获得的分辨率适用于系统范围。任何进程请求的最高分辨率都将处于活动状态,注意后果。
2. Going to 0.5 ms resolution:
2. 进入 0.5 ms 分辨率:
You may obtain 0.5 msresolution by means of the hidden API NtSetTimerResolution().
NtSetTimerResolution is exported by the native Windows NT library NTDLL.DLL. See How to set timer resolution to 0.5ms ?on MSDN. Nevertheless, the true achievable resoltion is determined by the underlying hardware. Modern hardware does support 0.5 ms resolution.
Even more details are found in Inside Windows NT High Resolution Timers. The supported resolutions can be obtained by a call to NtQueryTimerResolution().
您可以通过隐藏的 API获得 0.5 毫秒的分辨率NtSetTimerResolution()。NtSetTimerResolution 由本机 Windows NT 库 NTDLL.DLL 导出。请参阅如何将计时器分辨率设置为 0.5 毫秒?在 MSDN 上。然而,真正可实现的分辨率是由底层硬件决定的。现代硬件确实支持 0.5 毫秒的分辨率。更多细节可以在Inside Windows NT High Resolution Timers 中找到。支持的分辨率可以通过调用 NtQueryTimerResolution() 获得。
How to do:
怎么做:
#define STATUS_SUCCESS 0
#define STATUS_TIMER_RESOLUTION_NOT_SET 0xC0000245
// after loading NtSetTimerResolution from ntdll.dll:
// The requested resolution in 100 ns units:
ULONG DesiredResolution = 5000;
// Note: The supported resolutions can be obtained by a call to NtQueryTimerResolution()
ULONG CurrentResolution = 0;
// 1. Requesting a higher resolution
// Note: This call is similar to timeBeginPeriod.
// However, it to to specify the resolution in 100 ns units.
if (NtSetTimerResolution(DesiredResolution ,TRUE,&CurrentResolution) != STATUS_SUCCESS) {
// The call has failed
}
printf("CurrentResolution [100 ns units]: %d\n",CurrentResolution);
// this will show 5000 on more modern platforms (0.5ms!)
// do your stuff here at 0.5 ms timer resolution
// 2. Releasing the requested resolution
// Note: This call is similar to timeEndPeriod
switch (NtSetTimerResolution(DesiredResolution ,FALSE,&CurrentResolution) {
case STATUS_SUCCESS:
printf("The current resolution has returned to %d [100 ns units]\n",CurrentResolution);
break;
case STATUS_TIMER_RESOLUTION_NOT_SET:
printf("The requested resolution was not set\n");
// the resolution can only return to a previous value by means of FALSE
// when the current resolution was set by this application
break;
default:
// The call has failed
}
Note: The functionality of NtSetTImerResolution is basically mapped to the functions timeBeginPeriodandtimeEndPeriodby using the bool value Set(see Inside Windows NT High Resolution Timersfor more details about the scheme and all its implications). However, the multimedia suite limits the granularity to milliseconds and NtSetTimerResolution allows to set sub-millisecond values.
注意:NtSetTImerResolution 的功能基本上映射到函数timeBeginPeriod并timeEndPeriod使用 bool 值Set(有关该方案及其所有含义的更多详细信息,请参阅Windows NT 高分辨率计时器内部)。但是,多媒体套件将粒度限制为毫秒,而 NtSetTimerResolution 允许设置亚毫秒值。
回答by Kirsan
All replays here are about system timer resolution. But.net timers notrespect it. As author notice by himself:
这里的所有重播都是关于系统计时器分辨率的。但是.net 计时器不尊重它。正如作者本人所言:
that the runtime implements its own timer queue that is similar to the Timer Queue Timers, but never actually calls the Win32 functions.
运行时实现自己的计时器队列,类似于计时器队列计时器,但从未实际调用 Win32 函数。
And Jan pointed in comment.
Jan 在评论中指出。
So, answers above are good info, but not directly correlated to .net timers and therefore misleading people :(
因此,上面的答案是很好的信息,但与 .net 计时器没有直接关系,因此会误导人们:(
Short answer to both author questions is by design. Why did they decide to go this way? Feared about whole system performance? Who knows...
To not duplicate, see more info on both questions (and ways to implement precise
timers on .net) in Jan's correlated topic.
对作者问题的简短回答是设计使然。他们为什么决定走这条路?担心整个系统的性能?谁知道……
要不重复,请参阅 Jan 的相关主题中有关两个问题(以及在 .net 上实现精确计时器的方法)的更多信息。

