C/C++ 시간을 측정하기

2022. 1. 6. 07:00C&C++

  기준 시점 단위 해상도  
clock 프로세스 실행 ms 1ms C (time.h)
GetTickCount 시스템 시작 이후 ms 15.6ms WinAPI
GetTickCount64 시스템 시작 이후 ms 15.6ms WinAPI
timeGetTime 시스템 시작 이후 ms 타이머 인터럽트 정확도 WinAPI
QueryPerformanceCounter 타임스탬프 카운트 관련 100ns 1㎲ 이하 WinAPI
chrono ? ns까지 가능 1㎲ 이하 C++ 11 (chrono)

GetTickCount <-> GetTickCount64 는 반환값이 32비트냐, 64비트냐의 차이이다.

32비트를 ms 단위로 return하는 GetTickCount의 경우 시스템 시작 이후 49일 정도 지나면 값이 오버플로우되면서 초기화된다.

 

timeGetTime은 timeBeginPeriod 함수를 통해서 해상도를 최대 1ms까지 높일 수 있다.

원칙적으로는 프로그램 종료시에 timeEndPeriod 함수를 호출하여 다시 원복시켜야 한다.

 

코드는 다음과 같이 사용하면 된다.

//clock (time.h)
clock_t start = clock();
Sleep(1);
clock_t end = clock();
float time = (end - start) / 1000.0f;
cout << time << endl;

//QueryPerformanceCounter (windows.h)
LARGE_INTEGER start, end, timer;
QueryPerformanceFrequency(&timer);
QueryPerformanceCounter(&start);
for(int i=0; i<100; i++);
QueryPerformanceCounter(&end);
long long time = (end.QuadPart - start.QuadPart);
cout << time << endl;


//GetTickCount (windows.h)
DWORD start, end;
float time;
start = GetTickCount();
Sleep(1);
end = GetTickCount();
time = (end - start) / 1000.0f;
cout << time << endl;

//GetTickCount64 (windows.h)
ULONGLONG start, end;
float time;
start = GetTickCount64();
Sleep(1);
end = GetTickCount64();
time = (end - start) / 1000.0f;
cout << time << endl;

//timeGetTime (windows.h, #pragma comment(lib, "winmm.lib"))
timeBeginPeriod(1);
DWORD start, end;
float time;
start = timeGetTime();
Sleep(1);
end = timeGetTime();
time = (end - start)/1000.0f;
cout << time << endl;


//chrono (chrono)
chrono::system_clock::time_point start = chrono::system_clock::now();
//100~200ns 정도 시간 끌기
for (int i = 0; i < 50; i++);
chrono::system_clock::time_point end = chrono::system_clock::now();
chrono::nanoseconds time = chrono::duration_cast<chrono::nanoseconds>(end - start);
cout << time.count() << endl;

'C&C++' 카테고리의 다른 글

[C/C++] 파일 입출력  (0) 2022.01.06
C언어 문자열 처리  (0) 2022.01.06
랜덤을 구현하는 방법  (0) 2021.11.07
#pragma once  (0) 2021.10.25
enum class  (0) 2021.10.25