เราจะมาดูวิธีการใช้ clock() ใน C++ clock() นี้มีอยู่ในไฟล์ส่วนหัว time.h หรือ ctime เราจะหาเวลาที่ผ่านไปของกระบวนการโดยใช้ฟังก์ชัน clock()
เพื่อให้ได้เวลาที่ผ่านไป เราสามารถหาเวลาโดยใช้ clock() ที่จุดเริ่มต้น และจุดสิ้นสุดของ taks จากนั้นลบค่าเพื่อให้ได้ส่วนต่าง หลังจากนั้น เราจะหารส่วนต่างด้วย CLOCK_PER_SEC (จำนวน clock tick ต่อวินาที) เพื่อรับเวลาของโปรเซสเซอร์
ตัวอย่าง
#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