Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Cách đo thời gian thực thi hàm trong C

Ở đây ta sẽ xem cách tính thời gian tiến trình. Dùng hàm clock() trong header time.h.

Để lấy thời gian trôi qua: lấy clock() ở đầu và cuối tác vụ, trừ hai giá trị lấy hiệu. Sau đó chia cho CLOCKS_PER_SEC (số nhịp clock mỗi giây) để ra thời gian xử lý.

Ví dụ

#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;
}

Kết quả

Timer starts
Press enter to stop the counter
Timer ends
The program took 5.218000 seconds to execute