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

时间:2010-06-29 14:20:29

标签: c++ windows winapi timer driver

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

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

P.S。我知道如何将它设置为1ms。

P.P.S。我将它从C#更改为更一般的问题(感谢Hans)

系统计时器分辨率

6 个答案:

答案 0 :(得分:8)

NtSetTimerResolution

示例代码:

#include <windows.h>

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

...

ULONG currentRes;
NtSetTimerResolution(5000, TRUE, &currentRes);

ntdll.lib链接。

答案 1 :(得分:4)

可以通过隐藏的API NtSetTimerResolution()获得0.5 ms 分辨率。 NtSetTimerResolution由本机Windows NT库NTDLL.DLL导出。请参阅MSDN上的How to set timer resolution to 0.5ms ?。然而,真正可实现的解决方案由底层硬件决定。现代硬件支持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

}

注意:NtSetTImerResolution的功能基本上使用bool值timeBeginPeriod映射到函数timeEndPeriod Set(请参阅Inside Windows NT High Resolution Timers有关该计划及其所有影响的更多详细信息)。但是,多媒体套件将粒度限制为毫秒,NtSetTimerResolution允许设置亚毫秒值。

答案 2 :(得分:3)

使用timeBeginPeriod和timeSetEvent,你可以获得Win32 API的最佳效果是1毫秒。也许你的HAL可以做得更好,但这是学术性的,你不能用C#编写设备驱动程序代码。

答案 3 :(得分:1)

你需要一个高分辨率计时器..你可以在这里找到一些信息:http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx

编辑:可在此处找到更多信息:设置为十分之一毫秒; http://msdn.microsoft.com/en-us/library/aa964692(VS.80).aspx

答案 4 :(得分:0)

如果你使用python,我写了一个名为wres的库,它在内部调用了NtSetTimerResolution。

pip install wres

import wres

# Set resolution to 0.5 ms (in 100-ns units)
# Automatically restore previous resolution when exit with statement
with wres.set_resolution(5000):
    pass

答案 5 :(得分:-6)

Timer.Interval = 500;