How to use struct timeval to get the execution time in microseconds with C

1 Answer

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

/*
  struct timeval {
    long tv_sec;    // seconds
    long tv_usec;   // microseconds
};
*/

int main() {
    struct timeval timevalBefore, timevalAfter;  

    gettimeofday(&timevalBefore, NULL);
    
    for (int i = 0; i < 10000000; i++) ;

    gettimeofday(&timevalAfter, NULL);

    printf("%ld microseconds\n", timevalAfter.tv_usec - timevalBefore.tv_usec); 

    return 0;
}



/*
run:

19592 microseconds

*/

 



answered Mar 11, 2022 by avibootz

Related questions

1 answer 124 views
1 answer 104 views
1 answer 266 views
2 answers 145 views
2 answers 185 views
1 answer 160 views
160 views asked May 29, 2023 by avibootz
...