C# 如何在Windows 10 20H1及更高版本上更改setWaitableTimer精度
Windows 10 20H1()中的计时器分辨率似乎有所改变 如果您想使用sleep(),那么仍然可以通过使用timeBeginPeriod()函数获得合理的精度。这种方法似乎不适用于等待计时器。有人知道如何提高计时器的准确性吗 这是我正在使用的测试程序的摘录C# 如何在Windows 10 20H1及更高版本上更改setWaitableTimer精度,c#,c++,windows,C#,C++,Windows,Windows 10 20H1()中的计时器分辨率似乎有所改变 如果您想使用sleep(),那么仍然可以通过使用timeBeginPeriod()函数获得合理的精度。这种方法似乎不适用于等待计时器。有人知道如何提高计时器的准确性吗 这是我正在使用的测试程序的摘录 // class Results omitted for clarity - it sums the duration calls to timerCallback() and divides it by the number of t
// class Results omitted for clarity - it sums the duration calls to timerCallback() and divides it by the number of times it was called.
class Program
{
static Results m_Results = new Results();
// Windows API function imports
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod", SetLastError = true)]
public static extern uint TimeBeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod", SetLastError = true)]
public static extern uint TimeEndPeriod(uint uMilliseconds);
[DllImport("kernel32.dll")]
public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, CallBack pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);
// callback definition
public delegate bool CallBack(IntPtr lpArg, int dwTimerLowValue, int dwTimerHighValue);
// Main method, run when the application is run
static void Main(string[] args)
{
SafeWaitHandle handle = CreateWaitableTimer(IntPtr.Zero, false, "MyWaitabletimer");
CallBack myCallBack = new CallBack(Program.timerCallback); // This function records the time its executed in a global list
const int period = 40; // Fire the timer every 40 mS
long duetime = period * -10000; // Keep firing the timer for 4 seconds
TimeBeginPeriod(1); // *** This call appears to make no difference.
SetWaitableTimer(handle, ref duetime, period, myCallBack, IntPtr.Zero, false);
TimeEndPeriod(1); // *** This call appears to make no difference.
Thread.Sleep(4000);
Console.WriteLine("count = {0}", m_Results.getCount());
Console.WriteLine("total duration = {0}", m_Results.getTotalDuration());
Console.WriteLine("average = {0}", m_Results.getResults());
Console.WriteLine("Tests complete");
Console.ReadKey();
}
public static bool timerCallback(IntPtr lpArg, int dwTimerLowValue, int dwTimerHighValue)
{
m_Results.addDifference(DateTime.Now.Millisecond);
return true;
}
当我运行代码时,我得到的计数是84、85或86,总持续时间
TimeEndPeriod(1)代码>可能放在末尾?另外,您是否尝试过创建可等待的计时器高分辨率
我实际上没有考虑TimeEndPeriod的位置,我在最后尝试过(在GetKey调用之后,不幸的是没有任何更改。我刚刚尝试使用hi res标志,这也没有什么区别。如果尝试period=1
,会发生什么?线程1计数=256总持续时间=4983平均值=19.46484375测试complete@CodeGorilla“我尝试C++中的代码,但是……”您应该张贴代码,或者删除C++标签。