How to measure loop execution time (GCC) in C

1 Answer

0 votes
#include <stdio.h>
#include <time.h>

int main() {
    long sum = 0;
    
    clock_t begin = clock();
    for (int i = 0; i < 10000000; i++) {
        sum += i;
    }
    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("%f sec\n", time_spent);

    int i = 0;
    sum = 0;
    
    begin = clock();
    while (i < 10000000) {
        sum += i;
        i++;
    }
    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("%f sec\n", time_spent);

    return 0;
}




/*
run:

0.029202 sec
0.029534 sec

*/

 



answered May 29, 2023 by avibootz

Related questions

1 answer 256 views
1 answer 199 views
2 answers 175 views
1 answer 175 views
175 views asked Feb 21, 2022 by avibootz
1 answer 312 views
...