Adventure Time - Jake time()함수와 performance counter
본문 바로가기
Back-end/c,c++

time()함수와 performance counter

by bogyoi 2023. 12. 31.

 

일반 time()함수의 경우, 초단위 경과시간을 측정하여, 아주 짧은 시간의 경우 측정이 잘 되지 않는 단점이 있다.

 

그래서 milli, micro단위와 같이 더 작은 단위로 경과시간을 측정할 수 있는 Windows 운영체제의 performance counter를 사용할 수 있다.

 

이를 사용할 때에는 #include <Windows.h> 헤더 파일을 포함시켜야한다.

 

 

LARGE_INTEGER freq, t_before, t_after;
LONGLONG t_diff;
double elapsed_time;

// . . . 추가 정의


QueryPerformanceFrequency(&freq);  //CPU clock의 frequency를 기록 (초당 몇번 계수가 되는지 기록한다.)
QueryPerformanceCounter(&t_before);  //함수 실행 직전 시간 기록
//////////////////////////////////////여기서 함수 호출
QueryPerformanceCounter(&t_after); //함수 실행 직후 시간 기록

t_diff = t_after.QuadPart - t_before.QuadPart;  //틱개수 차이를 저장
elapsed_time = ((double)t_diff / freq.QuadPart); //double형으로 형변환하여 cpu clock 주파수로 나눠준다.

printf("%10.3lf[milliseconds]", elapsed_time*1000); //밀리초 단위로 출력

 

elapsed_time에 저장된 값은 초단위이므로, 밀리초 단위로 출력하기 위해 1000을 곱해줬다.

만약 마이크로초단위로 출력하고 싶다면 1000000를 곱하여 출력을 확인해 볼 수 있다.