Microsoft MVP성태의 닷넷 이야기
Windows: 269. GetSystemTimeAsFileTime과 GetSystemTimePreciseAsFileTime의 차이점 [링크 복사], [링크+제목 복사],
조회: 5764
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
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

Windows: 269. GetSystemTimeAsFileTime과 GetSystemTimePreciseAsFileTime의 차이점
; https://www.sysnet.pe.kr/2/0/13802




Windows - GetSystemTimeAsFileTime과 GetSystemTimePreciseAsFileTime의 차이점

우선, 이 차이점을 이해하려면 아래의 글을 먼저 읽어주시고. ^^

윈도우 운영체제의 시간 함수 (1) - GetTickCount와 timeGetTime의 차이점
; https://www.sysnet.pe.kr/2/0/11063

위의 글을 이해했다면 이제 GetSystemTimeAsFileTime의 동작 방식도 쉽게 알 수 있습니다.

GetSystemTimeAsFileTime function (sysinfoapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime

즉, GetSystemTimeAsFileTime은 timer interrupt가 tick을 업데이트하는 주기로 시간이 업데이트되는 것인데요, 따라서 다음과 같은 식으로 테스트해 보면,

#include <vector>
#include <Windows.h>

using namespace std;

ULONGLONG SubtractFileTime(const FILETIME& ftA, const FILETIME& ftB)
{
    ULARGE_INTEGER a, b;
    a.LowPart = ftA.dwLowDateTime;
    a.HighPart = ftA.dwHighDateTime;

    b.LowPart = ftB.dwLowDateTime;
    b.HighPart = ftB.dwHighDateTime;

    return (a.QuadPart - b.QuadPart);
}

int main()
{
    int count = 1000000;
    vector<FILETIME> ticks;

    for (int i = 0; i < count; i++)
    {
        FILETIME ft;
        GetSystemTimeAsFileTime(&ft);

        ticks.push_back(ft);
    }

    FILETIME oldTime = ticks[0];
    ULONGLONG elapsed;
    for (int i = 1; i < count; i++)
    {
        elapsed = SubtractFileTime(ticks[i], oldTime);
        oldTime = ticks[i];

        if (elapsed != 0)
        {
            printf("%lld\n", elapsed);
        }
    }
}

/* 출력 결과: Current timer interval" == 1ms인 경우
10049
9912
10000
10023
9990
9992
10069
9931
9990
10007
*/

대충, 10,000 범위로 값이 툭툭 튀고 있는데요, 저 값의 정확한 의미는 QueryPerformanceFrequency가 반환한 값이 있어야 해석이 가능합니다.

bool g_IsHighResolution = false;

__int64 GetQPCFreq()
{
    LARGE_INTEGER qpcRate;
    g_IsHighResolution = QueryPerformanceFrequency(&qpcRate); // 대개의 경우 g_IsHighResolution == true
    return qpcRate.QuadPart;
}

__int64 frequency = GetQPCFreq();
printf("QPC frequency: %lld\n", frequency); // 출력 결과: QPC frequency: 10000000

위의 결과에 따라 GetSystemTimeAsFileTime이 반환한 값의 1 단위는 1 / 10,000,000 초(0.1 마이크로 초, 100 나노 초)에 해당합니다. 따라서 10,000 주기로 값이 튀는 것은 1 / 1,000초, 즉 1ms 주기로 발생하는 timer interrupt마다 GetSystemTimeAsFileTime의 값이 바뀐다는 것을 의미합니다.

만약 timer interrupt 주기가 15.6ms인 경우라면, 약 156,000 단위로 값이 튀는 현상을 볼 수 있습니다.

결국 timer interrupt가 발생한 바로 그 순간에 100 나노 초 단위의 정밀도로 그 시간을 보관하게 되지만, 이후 1ms가 지나기까지는 그 값이 변경되지 않다가, 1ms가 지나서야 다시 그 시점의 시간을 100 나노 초 단위로 보여주는 식입니다.




GetSystemTimePreciseAsFileTime은, 예상할 수 있겠지만 Precise라는 단어가 들어간 것에서 좀 더 정밀한 시간을 나타낼 것이라고 예상할 수 있습니다.

GetSystemTimePreciseAsFileTime function (sysinfoapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime

실제로, 위의 예제 코드를 GetSystemTimeAsFileTime을 호출하는 것만 GetSystemTimePreciseAsFileTime으로 바꿔 실행해 보면,

int main()
{
    int count = 10;
    vector<FILETIME> ticks;

    for (int i = 0; i < count; i++)
    {
        FILETIME ft;
        GetSystemTimePreciseAsFileTime(&ft);

        ticks.push_back(ft);
    }

    // ...[생략]...
}

/* 출력 결과: Current timer interval"의 설정과 무관하게!
3
2
1
2
1
1
1

대략 0.1us마다 값이 튀는 것을 볼 수 있습니다. 즉 timer interrupt가 발생하는 것과 무관하게 현재 시간을 100ns 단위의 정밀도로 반환하고 있는 것입니다.

이 함수는 Windows 8 / Windows Server 2012부터 구현하고 있는데요, 이게 어떻게 가능하게 된 것일까요? ^^ 일단 윈도우 소스코드가 없어 구체적으로 어떻게 구현돼 있는지는 알 수 없지만, 그냥 제 추측으로 적어보자면... ^^

아마도, timer interrupt가 발생하는 주기로 기존처럼 시간을 업데이트하고 있지만, 바로 그 시점의 rdtsc 값을 보관한 다음 이후 GetSystemTimePreciseAsFileTime을 호출할 때 rdtsc의 변화를 계산해 마지막 timer interrupt가 발생한 시점의 값과 더해 반환하는 식이... 아닐까 싶습니다.

물론, 그렇게 하면 요즘 CPU의 경우 GHz 주기로 시간 정밀도가 나올 수 있는데요, 하지만 근래의 Windows 운영체제는 그 값을 정규화시켜 100ns에 맞춰서 제공하고 있습니다.

아무튼, 1 ~ 15.6ms 정도의 정밀도로 상관없다면 GetSystemTimeAsFileTime을 사용하고, 그 이상의 정밀도가 필요하다면 (보통) 0.1us 정밀도를 갖는 GetSystemTimePreciseAsFileTime을 사용하면 됩니다. (주의할 사항이 있는데, 일부 시스템에서는 Precise 함수가 정상적인 값을 반환하지 않는 문제가 있으므로, GetSystemTimeAsFileTime으로 보완하는 코드가 필요합니다.)




참고로, QueryPerformanceFrequency 함수가 대개의 경우 10000000을 반환하지만 환경에 따라 다른 값을 반환하기도 합니다. 가령 예전에 질문하셨던 분도 그렇고, 아래의 글을 테스트할 때만 해도,

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

QueryPerformanceFrequency가 3328129를 반환했었는데요, 이 차이는 Windows 10 build 1809부터 바뀐 것이니 유의하시기 바랍니다.

Windows 10부터 바뀐 QueryPerformanceFrequency, QueryPerformanceCounter
; https://www.sysnet.pe.kr/2/0/13035





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/7/2024]

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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923183오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921708.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920550개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921048개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201916990오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916805오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916497오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918251개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926125개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919049오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919241오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924446개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201918889오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920616오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918908오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919673오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922737오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922023Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920062VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916444오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919848Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918095오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201916962오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918311.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915608오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920785오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...