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

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232325닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232154C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232182Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232482닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232188닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232175닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232169오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232376닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232108개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232226닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232143오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232207오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232258닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232210닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232194닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232199닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232150VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232447닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232339닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232681닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232217오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232296닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232431닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232253닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...