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