> 백엔드 개발 > C++ > 본문

기본 clock_gettime 지원 없이 Windows에서 나노초 정밀도 타이밍을 어떻게 달성할 수 있습니까?

Susan Sarandon
풀어 주다: 2024-10-26 06:10:03
원래의
687명이 탐색했습니다.

How can I achieve nanosecond precision timing on Windows without native clock_gettime support?

clock_gettime을 Windows로 포팅

clock_gettime 함수는 나노초 정밀도로 현재 시간을 가져오는 방법을 제공하는 POSIX 표준 함수입니다. 단, Windows에서는 기본적으로 지원되지 않습니다.

Windows로 코드 포팅

clock_gettime을 사용하는 코드를 Windows로 포팅하려면 Win32를 사용하여 대체 기능을 구현하면 됩니다. API. 다음은 이를 수행하는 방법에 대한 예입니다.

<code class="C++">#include <Windows.h>

// Returns the file time offset for Windows.
LARGE_INTEGER getFILETIMEoffset() {
    SYSTEMTIME s;
    FILETIME f;
    LARGE_INTEGER t;

    s.wYear = 1970;
    s.wMonth = 1;
    s.wDay = 1;
    s.wHour = 0;
    s.wMinute = 0;
    s.wSecond = 0;
    s.wMilliseconds = 0;
    SystemTimeToFileTime(&amp;s, &amp;f);
    t.QuadPart = f.dwHighDateTime;
    t.QuadPart <<= 32;
    t.QuadPart |= f.dwLowDateTime;
    return (t);
}

// Replacement for clock_gettime function.
int clock_gettime(int X, struct timeval *tv) {
    LARGE_INTEGER t;
    FILETIME f;
    double microseconds;
    static LARGE_INTEGER offset;
    static double frequencyToMicroseconds;
    static int initialized = 0;
    static BOOL usePerformanceCounter = 0;

    if (!initialized) {
        LARGE_INTEGER performanceFrequency;
        initialized = 1;
        usePerformanceCounter = QueryPerformanceFrequency(&amp;performanceFrequency);
        if (usePerformanceCounter) {
            QueryPerformanceCounter(&amp;offset);
            frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
        } else {
            offset = getFILETIMEoffset();
            frequencyToMicroseconds = 10.;
        }
    }
    if (usePerformanceCounter) QueryPerformanceCounter(&amp;t);
    else {
        GetSystemTimeAsFileTime(&amp;f);
        t.QuadPart = f.dwHighDateTime;
        t.QuadPart <<= 32;
        t.QuadPart |= f.dwLowDateTime;
    }

    t.QuadPart -= offset.QuadPart;
    microseconds = (double)t.QuadPart / frequencyToMicroseconds;
    t.QuadPart = microseconds;
    tv->tv_sec = t.QuadPart / 1000000;
    tv->tv_usec = t.QuadPart % 1000000;
    return (0);
}</code>
로그인 후 복사

대체 기능을 구현한 후에는 코드에서 이를 사용하여 나노초 정밀도로 현재 시간을 얻을 수 있습니다. 다양한 플랫폼에서 clock_gettime 동작의 차이를 설명하기 위해 코드를 추가로 수정해야 할 수도 있습니다.

위 내용은 기본 clock_gettime 지원 없이 Windows에서 나노초 정밀도 타이밍을 어떻게 달성할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!