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)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241643닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241620닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241635닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241545닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241606닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241631오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241646디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241646오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241744닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241747디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242625오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241820닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241620Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241955닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241709VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241736닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241693닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242017닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...