Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 5개 있습니다.)
Windows: 120. 윈도우 운영체제의 시간 함수 (1) - GetTickCount와 timeGetTime의 차이점
; https://www.sysnet.pe.kr/2/0/11063

Windows: 121. 윈도우 운영체제의 시간 함수 (2) - Sleep 함수의 동작 방식
; https://www.sysnet.pe.kr/2/0/11065

Windows: 122. 윈도우 운영체제의 시간 함수 (3) - QueryInterruptTimePrecise, QueryInterruptTime 함수
; https://www.sysnet.pe.kr/2/0/11066

Windows: 123. 윈도우 운영체제의 시간 함수 (4) - RTC, TSC, PM Clock, HPET Timer
; https://www.sysnet.pe.kr/2/0/11067

Windows: 124. 윈도우 운영체제의 시간 함수 (5) - TSC(Time Stamp Counter)와 QueryPerformanceCounter
; https://www.sysnet.pe.kr/2/0/11068




윈도우 운영체제의 시간 함수 (3) - QueryInterruptTimePrecise, QueryInterruptTime 함수

지난 글을 통해, GetTickCount와 timeGetTime의 동작 방식을 살펴봤는데요. GetTickCount와 timeGetTime의 문제는 결국 운영체제가 메모리에 인터럽트가 발생할 때마다 그 횟수를 저장해 둔 변수의 값을 읽어온다는 것입니다. 그런데, 왜 그런 식으로 동작해야 할까요? 그냥 타이머 장치의 시간 값을 직접 구하는 Win32 API를 제공해주면 되는 것 아닐까요?

물론 이런 API가 있지만 아쉽게도 Windows 10부터 제공합니다.

QueryInterruptTimePrecise function
; https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryinterrupttimeprecise

lpInterruptTimePrecise [out]
A pointer to a ULONGLONG in which to receive the interrupt-time count in system time units of 100 nanoseconds. Divide by ten million, or 1e7, to get seconds (there are 1e9 nanoseconds in a second, so there are 1e7 100-nanoseconds in a second).


100 나노초 단위라고 하니, 만약 이 함수의 반환 값이 1,000이라고 했을 때 밀리 초로 환산하려면 10,000으로 나누어 0.1ms를 계산할 수 있습니다.

주기적인 타이머 인터럽트에 영향을 안 받는지... 실제로 다음의 예제로 테스트할 수 있습니다.

#include "stdafx.h"
#include <Windows.h>
// #include <realtimeapiset.h>

#pragma comment(lib, "winmm.lib")

typedef VOID (WINAPI *FuncQueryInterruptTimePrecise)(_Out_ PULONGLONG lpInterruptTimePrecise);

int main()
{
    int count = 0;

    HMODULE hModule = ::LoadLibrary(L"KernelBase.dll");

    FuncQueryInterruptTimePrecise func_QueryInterruptTimePrecise = 
        (FuncQueryInterruptTimePrecise)::GetProcAddress(hModule, "QueryInterruptTimePrecise");

    if (func_QueryInterruptTimePrecise == nullptr)
    {
        printf("Not a Windows 10 PC\n");
        return 0;
    }

    __int64 currentTime;
    __int64 gap[1000];

    count = -1;
    int maxCount = 100;
    __int64 diff = 0;

    printf("QueryInterruptTimePrecise\n");
    while (count ++ < maxCount)
    {
        func_QueryInterruptTimePrecise((PULONGLONG)&currentTime);
        gap[count] = currentTime;
        printf("%I64d\n", currentTime);
    }

    currentTime = gap[0];
    diff = 0;
    for (int i = 1; i < maxCount; i++)
    {
        diff = gap[i] - currentTime;
        printf("%I64d, %0.4f\n", diff, diff / 10000.0);
        currentTime = gap[i];
    }

    return 0;
}

while 반복문에서 QueryInterruptTimePrecise 함수로 시간 값을 보관한 그 간격을 출력한 결과는 다음과 같습니다.

2294, 0.2294
2612, 0.2612
2514, 0.2514
2473, 0.2473
2463, 0.2463
2499, 0.2499
2461, 0.2461
2445, 0.2445
3450, 0.3450
2648, 0.2648
2508, 0.2508
2436, 0.2436
2421, 0.2421
2424, 0.2424
2421, 0.2421
2449, 0.2449
2418, 0.2418
2415, 0.2415
2397, 0.2397
...[생략]...

timeBeginPeriod + timeGetTime의 조합도 1ms 단위의 변화만 감지할 수 있었던 것에 비하면, 타이머 장치에 직접 접근하는 덕분에 정밀도는 훨씬 높아졌습니다.

그런데, 왜 이 좋은 것을 그동안 제공하지 않았던 것일까요? 제 생각이지만, 윈도우 PC 환경에서 1ms 미만의 정밀도를 요구하는 작업이 그다지 크게 중요하다고 생각지는 않았던 것이 아닌가 싶습니다. 그 외에 또 하나 이유라면, 사실 QueryInterruptTimePrecise는 타이머 디바이스로부터 직접 값을 읽어오기 때문에 호출 시간이 timeGetTime에 비해 더 느리다는 단점이 있습니다. 즉, 시간 정밀도를 높이려고 호출한 API 자체가 시간이 더 걸려 버리는 상황이 발생하는 것입니다.




이와 유사한 함수의 이름으로 QueryInterruptTime이 있는데 역시 Windows 10부터 제공됩니다. 이 함수는 timeGetTime과 동작 방식은 유사하나 대신 값이 64비트 변수에 담겨있고 100ns 단위의 시간 값을 제공합니다.

실제로 기본 타이머 설정인 15.625ms로 테스트를 해보면,

#include "stdafx.h"
#include <Windows.h>
// #include <realtimeapiset.h>

#pragma comment(lib, "winmm.lib")

typedef VOID (WINAPI *FuncQueryInterruptTime)(_Out_ PULONGLONG lpInterruptTime);

int main()
{
    int count = 0;

    HMODULE hModule = ::LoadLibrary(L"KernelBase.dll");

    FuncQueryInterruptTime func_QueryInterruptTime =
        (FuncQueryInterruptTime)::GetProcAddress(hModule, "QueryInterruptTime");

    if (func_QueryInterruptTime == nullptr)
    {
        printf("Not a Windows 10 PC\n");
        return 0;
    }

    __int64 currentTime;
    __int64 gap[1000];

    count = -1;
    int maxCount = 100;
    __int64 diff = 0;

    printf("QueryInterruptTime\n");
    while (count++ < mxunt)
    {
        func_QueryInterruptTime((PULONGLONG)&curentTime);
        gap[count] = currentTime;
        printf("%I64d\n", currentTime);
    }

    currentTime = gap[0];
    diff = 0;
    for (int i = 1; i < maxCount; i++)
    {
        diff = gap[i] - currentTime;
        printf("%I64d, %0.4f\n", diff, diff / 10000.0);
        currentTime = gap[i];
    }

    return 0;
}

출력된 시간 간격은 GetTickCount 때의 결과와 유사하게 약 15.625ms 간격으로 변화가 발생합니다.

0, 0.0000
...[생략: 수십 번 반복]...
156319, 15.6319
...[생략]...

물론, 위의 소스 코드에서 timeBeginPeriod(1) 코드를 한 번 호출해 주면 QueryInterruptTime은 1ms 단위로 변합니다.

(첨부 파일은 이 글의 소스 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/14/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  [55]  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12241정성태6/23/202012289.NET Framework: 914. C# - Task.Yield 사용법파일 다운로드1
12240정성태6/23/202013571오류 유형: 622. 소켓 바인딩 시 "System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions" 오류 발생
12239정성태6/21/20209939Linux: 30. (윈도우라면 DLL에 속하는) .so 파일이 텍스트로 구성된 사례 [1]
12238정성태6/21/20209987.NET Framework: 913. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 라이브러리
12237정성태6/20/20209752.NET Framework: 912. 리눅스 환경의 .NET Core에서 "test".IndexOf("\0")가 0을 반환
12236정성태6/19/202010142오류 유형: 621. .NET Standard 대상으로 빌드 시 dynamic 예약어에서 컴파일 오류 - error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
12235정성태6/19/20209801오류 유형: 620. Windows 10 - Inaccessible boot device 블루 스크린
12234정성태6/19/20209496개발 환경 구성: 494. NuGet - nuspec의 패키지 스키마 버전(네임스페이스) 업데이트 방법
12233정성태6/19/20209183오류 유형: 619. SQL 서버 - The transaction log for database '...' is full due to 'LOG_BACKUP'. - 두 번째 이야기
12232정성태6/19/20208158오류 유형: 618. SharePoint - StoreBusyRetryLater 오류
12231정성태6/15/202010549.NET Framework: 911. Console/Service Application을 위한 SynchronizationContext - AsyncContext
12230정성태6/15/20209938오류 유형: 617. IMetaDataImport::GetMethodProps가 반환하는 IL 코드 주소(RVA) 문제
12229정성태6/13/202011798.NET Framework: 910. USB/IP PROJECT를 이용해 C#으로 USB Keyboard + Mouse 가상 장치 만들기 [1]
12228정성태6/12/202011865.NET Framework: 909. C# - Source Generator를 적용한 XmlCodeGenerator파일 다운로드1
12227정성태6/12/202015817오류 유형: 616. Visual Studio의 느린 업데이트 속도에 대한 원인 분석 [5]
12226정성태6/11/202013164개발 환경 구성: 493. OpenVPN의 네트워크 구성 [4]파일 다운로드1
12225정성태6/11/202012101개발 환경 구성: 492. 윈도우에 OpenVPN 설치 - 클라이언트 측 구성
12224정성태6/11/202019928개발 환경 구성: 491. 윈도우에 OpenVPN 설치 - 서버 측 구성 [1]
12223정성태6/9/202013990.NET Framework: 908. C# - Source Generator 소개 [10]파일 다운로드2
12222정성태6/3/20209890VS.NET IDE: 146. error information: "CryptQueryObject" (-2147024893/0x80070003)
12221정성태6/3/20209718Windows: 170. 비어 있지 않은 디렉터리로 symbolic link(junction) 연결하는 방법
12220정성태6/3/202012059.NET Framework: 907. C# DLL로부터 TLB 및 C/C++ 헤더 파일(TLH)을 생성하는 방법
12219정성태6/1/202011204.NET Framework: 906. C# - lock (this), lock (typeof(...))를 사용하면 안 되는 이유파일 다운로드1
12218정성태5/27/202011172.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법 [3]
12217정성태5/24/20209673오류 유형: 615. Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
12216정성태5/15/202012761.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기 [14]파일 다운로드1
... 46  47  48  49  50  51  52  53  54  [55]  56  57  58  59  60  ...