Microsoft MVP성태의 닷넷 이야기
Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime [링크 복사], [링크+제목 복사],
조회: 22019
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

윈도우의 GetTickCount와 리눅스의 clock_gettime

GetTickCount에 대한,

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

리눅스의 대응 함수를 찾는 중에 std::clock 함수가 눈에 들어왔습니다.

std::clock
; https://en.cppreference.com/w/cpp/chrono/c/clock

그래서 다음과 같이 테스트했더니,

clock_t dwStart = std::clock();
usleep(1000 * 1000); // 1초 sleep
clock_t dwEnd = std::clock();

clock_t dwDiff = dwEnd - dwStart;
printf("%d\n", dwDiff); // 출력 결과 0

0이 나옵니다. ^^; 왜냐하면, std::clock은 내부적으로 clock_gettime을 호출하는데, strace로 확인해 보면 CLOCK_PROCESS_CPUTIME_ID로 호출하는 것과 같습니다.

struct timespec tspec;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tspec); // == std::clock();

인자가 의미하는 바에 따라,

/* High-resolution timer from the CPU.  */
# define CLOCK_PROCESS_CPUTIME_ID	2

/* Thread-specific CPU-time clock.  */
# define CLOCK_THREAD_CPUTIME_ID	3

이것은 해당 프로세서(CPU)를 사용한 시간을 반환하는 것으로 usleep 등으로 인해 작업을 하지 않은 경우에는 CPU 사용을 하지 않았으므로 0에 가까운 값을 반환하는 것입니다. 윈도우 환경으로 말하면 GetProcessTimes에 해당하는 것입니다.

그런데, 엄밀히 따지면 std::clock으로 유효하지 않은 값을 반환하는 경우가 발생할 수 있습니다. 가령 다음과 같은 상황에서,

clock_t dwStart = std::clock();
// ... 복잡한 작업 ...
clock_t dwEnd = std::clock();

중간의 작업을 하다가 스레드 문맥 전환이 발생해 다른 스레드가 해당 CPU에서 스케줄링되면 std::clock은 그 스레드가 수행한 작업량까지 더한 값을 반환하게 됩니다. 따라서 그런 문제를 없애고 싶다면 std::clock보다는 clock_gettime에 CLOCK_THREAD_CPUTIME_ID 옵션으로 직접 호출하는 것이 맞을 것입니다.

struct timespec tspec;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tspec); // 윈도우의 GetCpuTimes




GetTickCount에 해당하는 작업은 clock_gettime에 CLOCK_REALTIME_COARSE를 주면 됩니다.

/* Identifier for system-wide realtime clock, updated only on ticks.  */
# define CLOCK_REALTIME_COARSE      5

clock_gettime(CLOCK_REALTIME_COARSE, &tspec); // 윈도우의 GetTickCount();

또는, 윈도우의 QueryPerformanceCounter라면 CLOCK_MONOTONIC을 주는 것이 그나마 의미상 비슷할 것입니다.

/* Monotonic system-wide clock.  */
# define CLOCK_MONOTONIC		1

clock_gettime(CLOCK_MONOTONIC, &tspec); // 윈도우의 QueryPerformanceCounter();

참고로, CLOCK_MONOTONIC과 유사하게 CLOCK_REALTIME이 있긴 한데,

/* Identifier for system-wide realtime clock.  */
# define CLOCK_REALTIME         0

주석에서 보는 바와 같이,

System-wide clock that measures real (i.e., wall-clock) time. Setting this clock requires appropriate privileges. This clock is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), and by the incremental adjustments performed by adjtime(3) and NTP.


구간의 시간을 취합하기에는 적절한 옵션이 아닙니다.




그런데, clock_gettime을 이용해 구간 내 시간을 측정하려면 약간의 계산을 요합니다. 가령, 다음과 같이 시간 측정을 하면,

struct timespec s_tspec;
struct timespec e_tspec;

{
    clock_gettime(CLOCK_MONOTONIC, &s_tspec);
    usleep(1500 * 1000);
    clock_gettime(CLOCK_MONOTONIC, &e_tspec);
}

timespec 구조체는,

/* POSIX.1b structure for a time value.  This is like a `struct timeval' but
   has nanoseconds instead of microseconds.  */
struct timespec
{
  __time_t tv_sec;		/* Seconds.  */
  __syscall_slong_t tv_nsec;	/* Nanoseconds.  */
};

흐른 시간 값에 대해 초와 나노초 단위로 분리해 보관하고 있기 때문에 다음과 같은 식으로 흐른 시간을 계산해야 합니다.

// Profiling Code Using clock_gettime
// ; https://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/

#define NANO_PER_SEC ((__clock_t) 1000000000)

timespec diff(timespec start, timespec end)
{
    timespec temp;
    if ((end.tv_nsec - start.tv_nsec) < 0) {
        temp.tv_sec = end.tv_sec - start.tv_sec - 1;
        temp.tv_nsec = NANO_PER_SEC + end.tv_nsec - start.tv_nsec;
    }
    else {
        temp.tv_sec = end.tv_sec - start.tv_sec;
        temp.tv_nsec = end.tv_nsec - start.tv_nsec;
    }
    return temp;
}

그리고 그 timespec을 다시 특정 시간 단위로 환산해서 구할 수 있습니다.

#define NANO_PER_MILLI  ((__clock_t) 1000000)
#define MILLI_PER_SEC  ((__clock_t) 1000)

clock_t gettotalnanosec(const timespec& time)
{
    return time.tv_sec * NANO_PER_SEC + time.tv_nsec;
}

clock_t gettotalmillisec(const timespec& time)
{
    return time.tv_sec * MILLI_PER_SEC + time.tv_nsec / NANO_PER_MILLI;
}

따라서, 대충 다음과 같은 식으로 구간별 시간을 측정할 수 있습니다.

{
    struct timespec s_tspec;
    struct timespec e_tspec;

    clock_gettime(CLOCK_MONOTONIC, &s_tspec);
    usleep(500 * 1000);
    clock_gettime(CLOCK_MONOTONIC, &e_tspec);

    timespec diffspec = diff(s_tspec, e_tspec);
    clock_t timeDiff = gettotalmillisec(diffspec);

    printf("%lu\n", timeDiff);
}

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/24/2019]

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

비밀번호

댓글 작성자
 




... [121]  122  123  124  125  126  127  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
10899정성태2/17/201623340개발 환경 구성: 282. kernel32.dll, kernel32legacy.dll, api-ms-win-core-sysinfo-l1-2-0.dll [1]
10898정성태2/17/201621791.NET Framework: 547. PerformanceCounter의 InstanceName 지정 시 주의 사항파일 다운로드1
10897정성태2/17/201621111디버깅 기술: 76. windbg 분석 사례 - 닷넷 프로파일러의 GC 콜백 부하
10896정성태2/17/201622291오류 유형: 320. FATAL: 28000: no pg_hba.conf entry for host "fe80::1970:8120:695:a41e%12"
10895정성태2/17/201621083.NET Framework: 546. System.AppDomain으로부터 .NET Profiler의 AppDomainID 구하는 방법 [1]
10894정성태2/17/201621819오류 유형: 319. Visual Studio에서 찾기는 성공하지만 해당 소스 코드 정보가 보이지 않는 경우
10893정성태2/16/201620459.NET Framework: 545. 닷넷 - 특정 클래스가 로드되었는지 여부를 알 수 있을까? - 두 번째 이야기
10892정성태2/16/201621086오류 유형: 318. 탐색기에서 폴더 생성/삭제 시 몇 초 동안 멈추는 현상
10891정성태2/16/201624100VC++: 95. 내 CPU가 MPX/SGX를 지원할까요? [1]
10890정성태2/15/201623958.NET Framework: 544. C# 5의 Caller Info를 .NET 4.5 미만의 응용 프로그램에 적용하는 방법 [5]
10889정성태2/14/201620259.NET Framework: 543. C++의 inline asm 사용을 .NET으로 포팅하는 방법 - 두 번째 이야기파일 다운로드1
10888정성태2/14/201618622.NET Framework: 542. 닷넷 - 특정 클래스가 로드되었는지 여부를 알 수 있을까?
10887정성태2/3/201619276VC++: 94. MPX(Memory Protection Extensions) 테스트파일 다운로드1
10886정성태2/3/201620515개발 환경 구성: 281. Intel MPX Runtime Driver 수동 설치
10885정성태2/2/201620203오류 유형: 317. Sybase.Data.AseClient.AseException: The command has timed out.
10884정성태1/11/201621430개발 환경 구성: 280. 닷넷에서 SAP Adaptive Server Enterprise 데이터베이스 사용파일 다운로드1
10882정성태1/6/201620724Windows: 113. 윈도우의 2179, 26143, 47001 TCP 포트 사용 [1]
10881정성태1/3/201622161오류 유형: 316. 윈도우 10 - 바탕/돋음 체가 사라져 한글이 깨지는 현상 [2]
10880정성태12/16/201519832오류 유형: 315. 닷넷 프로파일러의 오류 코드 정보
10879정성태12/16/201521753오류 유형: 314. Error : DEP0700 : Registration of the app failed. error 0x80070005
10878정성태12/9/201524831디버깅 기술: 75. UWP(유니버설 윈도우 플랫폼) 앱에서 global::System.Diagnostics.Debugger.Break 예외 발생 시 대응 방법
10877정성태12/9/201529269VC++: 93. std::thread 사용 시 R6010 오류 [2]
10876정성태11/26/201525315.NET Framework: 541. SignedXml을 이용한 ds:Signature만드는 방법 [3]파일 다운로드1
10875정성태11/26/201530311개발 환경 구성: 279. signtool.exe의 다중 서명 기능 [2]
10874정성태11/26/201526312개발 환경 구성: 278. 인증서와 인증서를 이용한 코드 사인의 해시 구분
10873정성태11/25/201525431.NET Framework: 540. C# - 부동 소수 계산 왜 이렇게 나오죠? (2) [3]파일 다운로드1
... [121]  122  123  124  125  126  127  128  129  130  131  132  133  134  135  ...