我想将机器计时器分辨率设置为0.5毫秒。
Sysinternal实用程序报告最小时钟分辨率为0.5毫秒,因此可以完成。
P.S. 我知道如何将其设置为1毫秒。
P.P.S. 我将其从C#更改为更一般的问题(感谢Hans)
系统计时器分辨率
示例代码:
#include <windows.h>
extern "C" NTSYSAPI NTSTATUS NTAPI NtSetTimerResolution(ULONG DesiredResolution, BOOLEAN SetResolution, PULONG CurrentResolution);
...
ULONG currentRes;
NtSetTimerResolution(5000, TRUE, ¤tRes);
使用ntdll.lib
库进行链接。
NtSetTimerResolution()
获得0.5毫秒的分辨率。 NtSetTimerResolution由本机Windows NT库NTDLL.DLL导出。请参见MSDN上的如何将计时器分辨率设置为0.5ms?。然而,真正可实现的分辨率取决于底层硬件。现代硬件确实支持0.5毫秒的分辨率。更多详细信息请参阅《Windows NT高分辨率计时器内部》。可以通过调用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
}
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
你可以通过使用timeBeginPeriod和timeSetEvent函数调用来获得Win32 API中的最小时间间隔,其值为1毫秒。也许你的HAL可以做得更好,但这是学术上的问题,因为你不能使用C#编写设备驱动程序代码。
你需要一个高分辨率计时器。你可以在这里找到一些信息:http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx
编辑:更多信息可以在这里找到:设置为千分之一秒;http://msdn.microsoft.com/en-us/library/aa964692(VS.80).aspx
System.Diagnostics.Stopwatch
取代。 - Charlie Salts