여기서는 C++에서 clock()을 사용하는 방법을 살펴보겠습니다. 이 clock()은 time.h 또는 ctime 헤더 파일에 있습니다. 여기에서 이 clock() 함수를 사용하여 프로세스의 경과 시간을 찾을 수 있습니다.
경과 시간을 얻으려면 처음에 clock()을 사용하고 tak이 끝날 때 시간을 얻은 다음 값을 빼서 차이를 얻을 수 있습니다. 그런 다음 그 차이를 CLOCK_PER_SEC(초당 클록 틱 수)로 나누어 프로세서 시간을 구합니다.
예시
#include <iostream>
#include <ctime>
using namespace std;
void take_enter() {
cout << "Press enter to stop the counter" <<endl;
while(1) {
if (getchar())
break;
}
}
main() {
// Calculate the time taken by take_enter()
clock_t t;
t = clock();
cout << "Timer starts\n";
take_enter();
cout << "Timer ends \n";
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
cout << "The program took "<< time_taken <<" seconds to execute";
} 출력
Timer starts Press enter to stop the counter Timer ends The program took 3.546 seconds to execute