여기에서 프로세스에 소요된 시간을 계산하는 방법을 살펴보겠습니다. 이 문제에서는 clock() 함수를 사용합니다. clock()은 time.h 헤더 파일에 있습니다.
경과 시간을 얻으려면 작업 시작과 끝에서 clock()을 사용하여 시간을 얻은 다음 값을 빼서 차이를 얻을 수 있습니다. 그런 다음 그 차이를 CLOCK_PER_SEC(초당 클록 틱 수)로 나누어 프로세서 시간을 구합니다.
예시
#include <stdio.h>
#include <time.h>
void take_enter() {
printf("Press enter to stop the counter \n");
while(1) {
if (getchar())
break;
}
}
main() {
// Calculate the time taken by take_enter()
clock_t t;
t = clock();
printf("Timer starts\n");
take_enter();
printf("Timer ends \n");
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
printf("The program took %f seconds to execute", time_taken);
} 출력
Timer starts Press enter to stop the counter Timer ends The program took 5.218000 seconds to execute