Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วิธีวัดเวลาที่ฟังก์ชันใช้ในการทำงานใน C

ใช้ฟังก์ชัน clock() จาก time.h วัดเวลา CPU ที่ใช้

วิธีการ

  1. บันทึกเวลาเริ่มต้นด้วย clock()
  2. รันงานที่ต้องการวัด
  3. บันทึกเวลาสิ้นสุด และลบเพื่อหาความต่าง
  4. หารด้วย 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