如何将定时器分辨率设置为0.5毫秒?

Bop*_*Bop 5 c++ windows winapi driver timer

我想将机器计时器分辨率设置为0.5ms.

Sysinternal实用程序报告最小时钟分辨率为0.5ms,因此可以完成.

PS我知道如何设置为1ms.

PPS我把它从C#改为更一般的问题(感谢Hans)

系统计时器分辨率

Bop*_*Bop 8

NtSetTimerResolution

示例代码:

#include <windows.h>

extern "C" NTSYSAPI NTSTATUS NTAPI NtSetTimerResolution(ULONG DesiredResolution, BOOLEAN SetResolution, PULONG CurrentResolution);

...

ULONG currentRes;
NtSetTimerResolution(5000, TRUE, &currentRes);
Run Code Online (Sandbox Code Playgroud)

链接ntdll.lib.


Arn*_*rno 8

您可以通过隐藏的 API获得 0.5 毫秒的NtSetTimerResolution()分辨率。NtSetTimerResolution 由本机 Windows NT 库 NTDLL.DLL 导出。请参阅如何将计时器分辨率设置为 0.5ms?在 MSDN 上。然而,真正可实现的分辨率是由底层硬件决定的。现代硬件确实支持 0.5 毫秒分辨率。更多详细信息可以在Inside Windows NT High Resolution Timers中找到。可以通过调用 NtQueryTimerResolution() 来获取支持的分辨率。

怎么做:

#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

}
Run Code Online (Sandbox Code Playgroud)

注意:NtSetTImerResolution 的功能基本上通过使用 bool 值映射到函数timeBeginPeriod timeEndPeriod有关Set该方案及其所有含义的更多详细信息,请参阅“Windows NT 高分辨率定时器内部”)。然而,多媒体套件将粒度限制为毫秒,并且 NtSetTimerResolution 允许设置亚毫秒值。