ใช้ฟังก์ชัน clock() จาก time.h วัดเวลา CPU ที่ใช้
วิธีการ
- บันทึกเวลาเริ่มต้นด้วย
clock() - รันงานที่ต้องการวัด
- บันทึกเวลาสิ้นสุด และลบเพื่อหาความต่าง
- หารด้วย
CLOCKS_PER_SECเพื่อได้วินาที
ตัวอย่าง
#include <stdio.h>
#include <time.h>
void take_enter() {
printf("Press enter to stop the counter\n");
while (1) { if (getchar()) break; }
}
int main() {
clock_t t = clock();
printf("Timer starts\n");
take_enter();
printf("Timer ends\n");
t = clock() - t;
double time_taken = ((double)t) / CLOCKS_PER_SEC;
printf("The program took %f seconds to execute", time_taken);
return 0;
}
ผลลัพธ์
Timer starts Press enter to stop the counter Timer ends The program took 5.218000 seconds to execute