How to setup timer resolution to 0.5 ms?

前端 未结 5 1518
北荒
北荒 2021-01-03 03:44

I want to set a machine timer resolution to 0.5ms.

Sysinternal utility reports that the min clock resolution is 0.5ms so it can be done.

P.S. I know how to

5条回答
  •  心在旅途
    2021-01-03 04:46

    You may obtain 0.5 ms resolution 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().

    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 timeBeginPeriod and timeEndPeriod by using the bool value Set (see Inside Windows NT High Resolution Timers for 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.

提交回复
热议问题