대부분 함수의 시간을 측정하고 싶을 때 아래와 같이 코드를 작성하곤 한다.
#include <time.h>
#include <stdio.h>
int main()
{
clock_t start, end;
start = clock();
// 시간 측정을 실행할 함수..
end = clock();
printf("[time : %f]\\n", (float)(end - start)/CLOCKS_PER_SEC);
}
하지만 이때 사용되는 clock()은 cpu의 클럭수로 시간을 측정하기 때문에 정확한 시간이라고 하긴 어렵다.
예를들어 함수 중간에 sleep()
을 사용한다면, 그동안 프로그램은 전혀 동작하지 않기 때문에 정확한 시간측정이 어려울 수 있다.
그렇다면 sleep()중인 시간까지 포함한 프로그램은 어떻게 측정할 수 있을까?
이제 time()
함수에 대해 알아보자
time() 함수는 현재 캘린더 시간(초)을 판별한다.
#include <time.h>
time_t time(time_t *timeptr);
time() 함수는 현재 캘린더 시간을 리턴한다. 또한 리턴값도 timeptr에서 지정한 위치에 저장된다. (timeptr이 NULL인 경우 리턴값은 저장되지 않는다)
캘린더 시간을 사용할 수 없으면 값 (time_t)(-1)이 리턴된다.
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
time_t start, end;
time(&start);
sleep(2);
time(&end);
printf("time = %f\\n", (float)(end - start)); // 출력
return (0);
}