clock_t clock(void); 프로세스를 수행한 시점부터 얼마나 지났는지 확인하는 함수
입력 매개 변수 리스트
없음
반환 값
프로세스를 수행한 시점부터 흐른 시간 (단위는 clock)
clock 함수가 반환하는 시간은 프로세스를 수행한 시점부터 흐른 시간입니다. 이 때 단위는 clock으로 시스템마다 차이가 있습니다. 매크로 상수로 CLOCKS_PER_SEC를 통해 1clock이 어느 정도의 시간인지 알 수 있습니다.
사용 예
1 |
//C언어 표준 라이브러리 함수 가이드 //clock_t clock(void); 프로세스를 수행한 시점부터 얼마나 지났는지 확인하는 함수 //특정 알고리즘을 수행하는데 걸린 시간을 측정 #include <time.h> #include <stdio.h> int main(void) { clock_t st, et; int i, j, k; st = clock(); //시작 clock을 구함 for (i = 0; i<10; i++) { for (j = 0; j<1000; j++) { for (k = 0; k<1000; k++) { } } putchar('.'); } et = clock();//종료 clock을 구함 printf("%d clocks (%d clocks/second)\n", et - st, CLOCKS_PER_SEC); return 0; } |
출력
1 |
..........78 clocks (1000 clocks/second) |
하노이 타워 수행 시간 측정
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/* https://ehpub.co.kr C언어 표준 라이브러리 함수 가이드 clock_t clock(void); 프로세스를 수행한 시점부터 얼마나 지났는지 확인하는 함수 1초 = CLOCKS_PER_SEC CLOCK 실습: 하노이 타워 알고리즘을 수행하는데 걸린 시간을 측정 */ #include <time.h> #include <stdio.h> void Hanoi(int n, const char* src, const char* use, const char* dest); int main(void) { clock_t st, et; int costs[3] = { 0 }; for (int i = 0; i < 3; i++) { st = clock(); Hanoi(10 + i, "A", "B", "C"); et = clock(); costs[i] = et - st; } for (int i = 0; i < 3; i++) { printf("\nHanoi(%d)'s 수행 시간 %d clocks (1sec = %d clocks)\n", 10+i,costs[i], CLOCKS_PER_SEC); } return 0; } void Hanoi(int n, const char* src, const char* use, const char* dest) { if (n <= 0) { return; } Hanoi(n - 1, src, dest, use); printf("%s → %s\n", src, dest); Hanoi(n - 1, use, src, dest); } |
실행 결과
1 2 3 4 5 6 7 |
앞쪽 실행 결과 생략... Hanoi(10)'s 수행 시간 986 clocks (1sec = 1000 clocks) Hanoi(11)'s 수행 시간 1960 clocks (1sec = 1000 clocks) Hanoi(12)'s 수행 시간 3985 clocks (1sec = 1000 clocks) |